The common Java wisdom, perhaps wisdom is the wrong term, is to implement constant values as static final
fields. This approach makes sense for “constants” that are guaranteed to be stable. For example the class
Boolean implements two static final fields called TRUE and FALSE which represents the two instances of
that class. It would also make sense for a DAYS_IN_A_WEEK constant whose value probably is never
going to change5.
However, many so-called business “constants” change over time because the business rule changes.
Consider the following example: The Archon Bank of Cardassia (ABC) has always insisted that an account
has a minimum balance of $500 if it is to earn interest. To implement this, we could add a static field named
MINIMUM_BALANCE to the class Account that would be used in the member functions that calculate
interest. Although this would work, it isn’t flexible. What happens if the business rules change and
different kinds of accounts have different minimum balances, perhaps $500 for savings accounts but only
$200 for checking accounts? What would happen if the business rule were to change to a $500 minimum
balance in the first year, $400 in the second, $300 in the third, and so on? Perhaps the rule will be changed
to $500 in the summer but only $250 in the winter?6 Perhaps a combination of all of these rules will need to
be implemented in the future.
The point to be made is that implementing constants as fields isn’t flexible, a much better solution is to
implement constants as getter member functions. In our example above, a static (class) member function
called getMinimumBalance() is far more flexible than a static field called MINIMUM_BALANCE because we
can implement the various business rules in this member function and subclass it appropriately for various
kinds of accounts.
/**
Get the value of the account number. Account numbers are in the following
format: BBBBAAAAAA, where BBBB is the branch number and
AAAAAA is the branch account number.
*/
public long getAccountNumber()
{
return ( ( getBranchNumber() * 100000 ) + getBranchAccountNumber() );
}
/**
Set the account number. Account numbers are in the following
format: BBBBAAAAAA where BBBB is the branch number and
AAAAAA is the branch account number.
*/
public void setAccountNumber(int newNumber)
{
setBranchAccountNumber( newNumber % 1000000 );
setBranchNumber( newNumber / 1000000 );
}
Subscribe to:
Post Comments (Atom)

No comments:
Post a Comment