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?
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:If the Java application is running with
-ea
on the command-line, then assertions will be enabled. When the application reachesassert (initialBalance > 0);
, if initialBalance is less than 0 and assertions are enabled, ajava.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: