Java Reference
In-Depth Information
The act of translating an entire sentence into Pig Latin is not trivial. If written
in one big method, it would be very long and difficult to follow. A better solution,
as implemented in the PigLatinTranslator class, is to decompose the translate
method and use several other support methods to help with the task.
The translate method uses a Scanner object to separate the string into words.
Recall that one role of the Scanner class (discussed in Chapter 3) is to separate a
string into smaller elements called tokens. In this case, the tokens are separated by
space characters so we can use the default white space delimiters. The PigLatin
program assumes that no punctuation is included in the input.
The translate method passes each word to the private support method
translateWord . Even the job of translating one word is somewhat involved,
so the translateWord method makes use of two other private methods,
beginsWithVowel and beginsWithBlend .
The beginsWithVowel method returns a boolean value that indicates whether
the word passed as a parameter begins with a vowel. Note that instead of checking
each vowel separately, the code for this method declares a string that contains all
the vowels, and then invokes the String method indexOf to determine whether
the first character of the word is in the vowel string. If the specified character can-
not be found, the indexOf method returns a value of
1 .
The beginsWithBlend method also returns a boolean value. The body of the
method contains only a return statement with one large expression that makes
several calls to the startsWith method of the String class. If any of these calls
returns true, then the beginsWithBlend method returns true as well.
Note that the translateWord , beginsWithVowel , and beginsWithBlend
methods are all declared with private visibility. They are not intended to pro-
vide services directly to clients outside the class. Instead, they exist to help the
translate method, which is the only true service method in this class, to do
its job. By declaring them with private visibility, they cannot be invoked from
outside this class. If the main method of the PigLatin class attempted to invoke
the translateWord method, for instance, the compiler would issue an error
message.
Figure 7.4 shows a UML class diagram for the PigLatin program. Note the
notation showing the visibility of various methods.
Whenever a method becomes large or complex, we should consider decompos-
ing it into multiple methods to create a more understandable class design. First,
however, we must consider how other classes and objects can be defined to create
better overall system design. In an object-oriented design, method decomposition
must be subordinate to object decomposition.
 
Search WWH ::




Custom Search