Java Reference
In-Depth Information
to write a function, say anglicizeHundreds , to perform this service. We show
this method, together with function anglicize but modified to call the new
function, in Fig. 2.7.
In Fig. 2.7, function anglicize is finished, and we should test it before pro-
ceeding. But how do we do that? Look at function anglicizeHundreds in Fig.
2.7. We have “stubbed it in”, by which we mean that we have fixed it to return
something that allows us to test function anglicize . It does not produce the
English words for n , but it does produce n . With this function, for the call angli-
cize(2024) we expect to get the value "2 thousand 24" . Writing anglicize-
Hundreds in this fashion allows us to test function anglicize thoroughly before
In fact, if you test anglicize thoroughly, looking at “extreme” cases like n
= 999 , n = 1000 , n = 1001 , n = 999999 , you will find an error. Calling angli-
cize(1000) yields the value "1 thousand 0" , and the 0 does not belong at the
end. The problem is that we wrote anglicizeHundreds to handle an integer n in
the range 0<n<1000 , but it is called at least once with n=0 . We should change
the specification on anglicizeHundreds so that it accepts integers in the range
0..1000 and also state expressly (in the specification) that the English equiva-
lent of 0 is the empty String "" .
In general, when programming and testing incrementally, compile often:
every few lines. Test just as often: as soon as you have written the specification
and header of a method, you can write a test for it. To facilitate testing, after writ-
ing the specification and header of a new method, write a body that is simple and
short but that allows you to test the parts of the program that call it.
The development of function anglicizeHundreds proceeds along similar
lines, so we do not show it. As you proceed, you will find the need for other func-
tions, e.g. a function teenName(n) that produces the English equivalent of n in
the range 10..19 and a function tensName(n) for n in the range 0..9 .
A procedural approach
The above development focused on introducing more and more functions,
/** = English equivalent of n , for 0<n<1,000,000 */
public static String anglicize( int n) {
if (n >= 1000)
{ return anglicizeHundreds(n / 1000); +
“ thousand “ + anglicizeHundreds(n % 1000);}
else { return anglicizeHundreds(n % 1000); }
/** = English equivalent of n , for 0<n<1,000 */
public static String anglicizeHundreds( int n)
{ return "" + n; }
Figure 2.7:
Function anglicize with stubbed-in function anglicizeHundreds
Search WWH ::

Custom Search