Reputation: 21
I am currently trying to work on a project that includes creating a BankAccount system. This system allows you to create a new bank account where you state who it belongs to, the balance, etc.
One of the methods is being able to withdraw money from the account. As well as this, you are able to check if the account has an overdraft or not.
For the withdraw
method, I have to meet several conditions. These are the following:
At the moment, I have been able to make it so the method will return false, if the amount is below 0.0. This is shown below:
public boolean withdraw (double amount) {
if (hasOverdraft) {
this.balance -= amount;
return true;
} else if (amount > 0.0) {
this.balance -= amount;
return true;
} else {
return false;
}
}
However, I have tried several different things to make it work with the overdraft but can't seem to do it.
Bear in mind that at the end, the method needs to be able to:
The overdraft can be checked with the following code:
if (hasOverdraft)
To check the code is working, we are using the following code:
public static void main (String[] args) {
BankAccount lewis = new BankAccount("1234", "Lewis", false);
System.out.println(lewis);
lewis.setBalance(200);
System.out.println(lewis);
lewis.withdraw(250);
System.out.println(lewis);
}
The "false" for BankAccount is showing that the account doesn't have an overdraft. We will test it with both false and true.
Upvotes: 0
Views: 185
Reputation: 15706
So much complexity in software comes from trying to make one thing do two things. -Ryan Singer
Your method does basically two things:
Separating those two concerns makes the code more concise, avoids replication of the actual action, and allows for extracting the two things into separate reusable methods if called for later:
public boolean withdraw (double amount) {
boolean canWithdraw = amount> 0 && (hasOverdraft || balance >= amount);
if (canWithdraw ) {
balance -= amount;
}
return canWithdraw;
}
As the commenters on the question already stated, you had a mistake in the precondition (checking the amount instead of the balance after withdrawing the amount).
Upvotes: 1