Assertion in Java for AP C.S. homework

107 Views Asked by At

I'm creating a simple bank account class, "BankAccount". The goal is to enhance the class to make sure that desired values are reached. For example, when constructing a new object of the class the constructor requires that the initial balance is greater than $0. It asks you to use assertion

public class BankAccount 
{

priavte int balance;

public BankAccount(int initialBalance)
{
    assert (initialBalance > 0);
    balance = initialBalance; 
}
}    

Is this the proper way to use assertion? And what exactly will the assert statement do if InitialBalance < 0?

2

There are 2 best solutions below

0
On BEST ANSWER

This is not the right way to use assertions. In fact, Oracle has made clear that assertions should not check method parameters, and more importantly, one should never assert the result of a function call with a side effect (since there are no guarantees it will actually be executed).

They are designed to be used to check invariants (for example, a list class might include some elements and an int length, and that length must be equal to the number of elements). Another example of the correct use:

public Foo acquireFoo(int id) {
  Foo result = null;
  if (id > 50) {
    result = fooService.read(id);
  } else {
    result = new Foo(id);
  }
  assert result != null;

  return result;
}

If the Java application is running with -ea on the command-line, then assertions will be enabled. When the application reaches assert (initialBalance > 0);, if initialBalance is less than 0 and assertions are enabled, a java.lang.AssertionError will be thrown. If -ea is not passed, then the assertion error will not be thrown.

It would be wiser to throw a java.lang.IllegalArgumentException as follows:

public BankAccount(int initialBalance)
{
    if (initialBalance < 0){
        throw new IllegalArgumentException("The initial balance may not be negative.");
    }
    balance = initialBalance; 
}
0
On

You can use an existing framework for tests that has a lot of common assertions in it.