|
home—info—labs—hws—exams
textbook—java.lang docs—java.util docs—archive
Consider BankAccount fees -- The first few transactions/mo were free (say, the first 4); after that there was a fee (say, $2.50). Our code included the numbers 4 and $2.50 in the middle of the code, perhaps in several different places. What if the bank manager decides to raise the fees? Or change the number of free-transactions?
Well, we an always search-replace, right? Careful — $2.50 might have been used for some other purposes! You need to go through the bank's entire code, and look at each "2.50" (and 2.5 and 5.0/2), and decide whether it th transaction fee, and if so change it. This process is tedious, and error-prone.
The proper solution is to use named constants:
public static final FREE_TRANSACTIONS_PER_MONTH = 4; public static final TRANSACTION_FEE = 2.50; public static final ATM_FEE = 2.50;
To see this visually, in BlueJ:
Another example: Roach population.
class RoachPopulation { int numRoaches; RoachPopulation( int initialPop ) { numRoaches = initialPop; } void spray() { numRoaches = numRoaches/10; } void grow() { numRoaches = numRoaches + numRoaches/10; } int getNumRoaches() { return numRoaches; } } |
class PrezElect is used to keep track of presidential election results, assuming there are exactly two candidates.
What fields do we want? What methods? Write 'em!
Introduce/compare:
n = n+1; n += 1; ++n; n++; |
Now, suppose this class is actually used by the electoral college, which has 435+100+3 electors. Make a named constant, to reflect this.
Extra: make further named constants which explain where each part of 435+100+3 comes from! lect06b-soln.html
1 Either: call the constructor in Code Pad, and then drag the tiny-red-box leftward to the bench; or, call the constructor by right-clicking on the class. ↩
home—info—labs—hws—exams
textbook—java.lang docs—java.util docs—archive
©2008, Ian Barland, Radford University Last modified 2008.Oct.13 (Mon) |
Please mail any suggestions (incl. typos, broken links) to ibarlandradford.edu |