Page 340 - Introduction to Programming with Java: A Problem Solving Approach
P. 340
306 Chapter 8 Software Engineering
Thus, instead of repeating the complete code for these four tasks in the constructor each time color selection is needed, you should put this color-selection code in a separate helper method and then call that method whenever color selection is needed. Study the Shirt program and sample session in Figures 8.3, 8.4a, and 8.4b, especially the public constructor, Shirt, and the private helper method, selectColor. Note how the constructor calls the selectColor method twice. In this particular case (and in the previous section’s Student class), the helper method calls are from a constructor. You can also call a helper method from any ordinary method in the same class.
There are two main benefits to using helper methods:
First, by moving some of the details from public methods into private methods, they enable the public methods to be more streamlined. That leads to public methods whose basic functionality is more apparent. And that in turn leads to improved program readability.
Second, using helper methods can reduce code redundancy. Why is that? Assume that a particular task (such as color input validation) needs to be performed at several places within a program. With a helper method, the task’s code appears only once in the program, and whenever the task needs to be performed, the helper method is called. On the other hand, without helper methods, whenever the task needs to be performed, the task’s complete code needs to be repeated each time the task is done.
/******************************************
*
ShirtDriver.java
Dean & Dean
*
Apago PDF Enhancer
*
*
This is a driver for the Shirt class.
******************************************/
public class ShirtDriver
{
}
// end ShirtDriver
public static void main(String[] args)
{
Shirt shirt = new Shirt();
System.out.println();
shirt.display();
} // end main
Sample session:
Enter person's name: Corneal Conn
Enter shirt's primary color (w, r, y): m
Enter shirt's primary color (w, r, y): r
Enter shirt's trim color (w, r, y): w
Corneal Conn's shirt:
red with white trim
Figure 8.3
ShirtDriver class and associated sample session