Lewis Pickles
Lewis Pickles

Reputation: 21

How to check more than one condition in a method and do something based on it's return value

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

Answers (1)

Peter Walser
Peter Walser

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:

  • check if you can withdraw money from the account (precondition), that's the case when overdrawing is allowed, or the balance won't become negative. The amount to withdraw should also be positive, and may not be zero (see comment by @forpas) - this can be part of the precondition, or just an argument validation step before.
  • actually withdraw the money when you can (action).

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

Related Questions