Java Reference
In-Depth Information
validates the amount to a private method, isValidAmount() ,which is used internally by the Account class. It checks
if an amount being used for credit or debit is not a negative number, not a NaN , and not infinity. These three criteria
for a number to be a valid number apply only to the Account class, and no other class needs to be using them. This is
the reason you need to declare this method private . Declaring it private has another advantage. In the future, you
may make a rule that you must credit or debit a minimum of 10 from any account. At that time, you could just change
the private isValidAmount() method and you are done. If you had made this method public , it would affect all
the client code, which was using it to validate an amount. You may not want to change the criteria for a valid amount
globally. To keep the effect of a change localized in a class, when the business rules change, you must implement a
method as private. You can implement this logic in your Account class as follows (only changed code is shown):
// Account.java
package com.jdojo.cls;
public class Account {
/* Other code goes here */
public int credit(double amount) {
// Make sure credit amount is valid
if (!this.isValidAmount(amount, "credit")) {
return -1;
}
/* Other code goes here */
}
public int debit(double amount) {
// Make sure debit amount is valid
if (!this.isValidAmount(amount, "debit")) {
return -1;
}
/* Other code goes here */
}
// Use a private method to validate credit/debit amount
private boolean isValidAmount(double amount, String operation) {
// Make sure amount is not negative, NaN or infinity
if (amount < 0.0 || Double.isNaN(amount) || Double.isInfinite(amount)) {
System.out.println("Invalid " + operation + " amount: " + amount);
return false;
}
return true;
}
}
Note that you might have implemented the credit() method ( debit() method as well) in a simpler way using
the following logic:
if (amount >= 0) {
this.balance = this.balance + amount;
return 1;
}
 
Search WWH ::




Custom Search