Java - Access Level-A Case Study

Introduction

The following code adds private Instance Variable and Public Methods to Account class.

private double balance;

It uses the private to hide its member field from outside. The only way to access balance value is via public method.

It guards the internal state by checking the parameter value:

Make sure credit amount is not negative, NaN or infinity

if (amount < 0.0 || Double.isNaN(amount) || Double.isInfinite(amount)) {
      System.out.println("Invalid credit amount: " + amount);
      return -1;
}

Make sure the debit amount is not negative, NaN or infinity */

if (amount < 0.0 || Double.isNaN(amount) || Double.isInfinite(amount)) {
      System.out.println("Invalid debit amount: " + amount);
      return -1;
}

Make sure a minimum balance of zero is maintained

if (this.balance < amount) {
      System.out.println("Insufficient fund. Debit attempted: " + amount);
      return -1;
}
    

Demo

class Account {
  private double balance;

  public double getBalance() {
    // Return the balance of this account
    return this.balance;
  }//  ww  w.java2s . c  o  m

  public int credit(double amount) {
    // Make sure credit amount is not negative, NaN or infinity
    if (amount < 0.0 || Double.isNaN(amount) || Double.isInfinite(amount)) {
      System.out.println("Invalid credit amount: " + amount);
      return -1;
    }

    // Credit the amount
    System.out.println("Crediting amount: " + amount);
    this.balance = this.balance + amount;
    return 1;
  }

  public int debit(double amount) {
    // Make sure the debit amount is not negative, NaN or infinity */
    if (amount < 0.0 || Double.isNaN(amount) || Double.isInfinite(amount)) {
      System.out.println("Invalid debit amount: " + amount);
      return -1;
    }

    // Make sure a minimum balance of zero is maintained
    if (this.balance < amount) {
      System.out.println("Insufficient fund. Debit attempted: " + amount);
      return -1;
    }

    // Debit the amount
    System.out.println("Debiting amount: " + amount);
    this.balance = this.balance - amount;
    return 1;
  }
}

public class Main {
  public static void main(String[] args) {
    Account ac = new Account();
    double balance = ac.getBalance();
    System.out.println("Balance = " + balance);

    // Credit and debit some amount
    ac.credit(1.1);
    ac.debit(1.12);

    balance = ac.getBalance();
    System.out.println("Balance = " + balance);

    // Attempt to credit and debit invalid amounts
    ac.credit(-2.90);
    ac.debit(Double.POSITIVE_INFINITY);
    balance = ac.getBalance();
    System.out.println("Balance = " + balance);

    // Attempt to debit more than the balance
    ac.debit(3.00);

    balance = ac.getBalance();
    System.out.println("Balance = " + balance);
  }
}

Result

Related Topic