Java Reference
In-Depth Information
Try This 4-1 Creating a Help Class
If one were to try to summarize the essence of the class in one sentence, it might be this:
a class encapsulates functionality. Of course, sometimes the trick is knowing where one
“functionality” ends and another begins. As a general rule, you will want your classes to be
the building blocks of your larger application. In order to do this, each class must represent
a single functional unit that performs clearly delineated actions. Thus, you will want your
classes to be as small as possible—but no smaller! That is, classes that contain extraneous
functionality confuse and destructure code, but classes that contain too little functionality
are fragmented. What is the balance? It is at this point that the science of programming be-
comes the art of programming. Fortunately, most programmers find that this balancing act
becomes easier with experience.
To begin to gain that experience you will convert the help system from Try This 3-3 in
the preceding chapter into a Help class. Let's examine why this is a good idea. First, the
help system defines one logical unit. It simply displays the syntax for Java's control state-
ments. Thus, its functionality is compact and well defined. Second, putting help in a class
is an esthetically pleasing approach. Whenever you want to offer the help system to a user,
simply instantiate a help-system object. Finally, because help is encapsulated, it can be up-
graded or changed without causing unwanted side effects in the programs that use it.
1. Create a new file called HelpClassDemo.java. To save you some typing, you might
want to copy the file from Try This 3-3 , Help3.java , into HelpClassDemo.java .
2. To convert the help system into a class, you must first determine precisely what con-
stitutes the help system. For example, in Help3.java , there is code to display a menu,
input the user's choice, check for a valid response, and display information about the
item selected. The program also loops until the letter q is pressed. If you think about
it, it is clear that the menu, the check for a valid response, and the display of the in-
formation are integral to the help system. How user input is obtained, and whether
repeated requests should be processed, are not. Thus, you will create a class that dis-
plays the help information, the help menu, and checks for a valid selection. Its meth-
ods will be called helpOn( ) , showMenu( ) , and isValid( ) , respectively.
Search WWH ::




Custom Search