OO Programming with Java


Assertions

Assertions are based on exceptions and are defined with the assert keyword:

public void register(String name,double price,int quantity) {
  assert quantity > 0 : "NEGATIVE QUANTITY: "+quantity;
  assert price    > 0 : "NEGATIVE PRICE: "+price;
  assert ! hasProduct(name) : "PRODUCT ALREADY EXIST: "+name;
  this.add(new Product(name,price,quantity));
}

Nb. The -ea option has then to be used with the java command to enable assertions.

As a illustration, the following program

bookstore.register("Java handbook", 6.55, -3);

displays:

NEGATIVE QUANTITY: -3

5 - 12