Using assertion to test the precondition
java
Solution
/**
Constructs a bank account with a zero balance.
*/
public BankAccount()
{
this(0);
}
/**
Constructs a bank account with a given balance.
@param initialBalance the initial balance
*/
public BankAccount(double initialBalance)
{
assert initialBalance >= 0;
balance = initialBalance;
}
Creating any illegal `BankAccount` immediately results in an exception (if assertions are enabled).
Assertions can be placed practically everywhere in the code. They are for debugging purposes and will have no effect if you disable them (e.g. during production).
If the purpose of the bankaccount is to always be positive, you might want to add additional assertions, for example:
/**
Withdraws money from the bank account.
@param amount the amount to withdraw
*/
public void withdraw(double amount)
{
assert amount <= this.balance;
this.balance -= amount;
}
Again, assertions are only for debugging, you should not try to catch them. Any assertion-exception indicates a fault in your program (or a fault in the assertion statement).
So the following should NOT be used:
try
{
BankAccount newbankaccount = new BankAccount(5);
newbankaccount.withdraw(6.0);
}
catch (Exception e)
{
// illegal withdrawal
}
Instead, you should check the pre-conditions.
BankAccount newbankaccount = new BankAccount(5);
if (newbankaccount.getBalance() < 6.0)
{
// illegal withdrawal
}
else
newbankaccount.withdraw(6.0);
An assertion-exception should only fire if there is a logic error in your application.
Problem
I am working on a school assignment, I am supposed to use assertions to test the preconditions of the deposit method and the constructor. I figured out the method, but I am stuck on how to add to the constructor. Here is what I have so far: ``` /** A bank account has a balance that can be changed by deposits and withdrawals. */ public class BankAccount { private double balance; /** Constructs a bank account with a zero balance. */ public BankAccount() { balance = 0; } /** Constructs a bank account with a given balance. @param initialBalance the initial balance */ public BankAccount(double initialBalance) { balance = initialBalance; } /** Deposits money into the bank account. @param amount the amount to deposit */ public void deposit(double amount) { assert amount >=0; double newBalance = balance + amount; balance = newBalance; } /** Withdraws money from the bank account. @param amount the amount to withdraw */ public void withdraw(double amount) { double newBalance = balance - amount; balance = newBalance; } /** Gets the current balance of the bank account. @return the current balance */ public double getBalance() { return balance; } } ```