Java Reference
In-Depth Information
An algorithm is often described using
pseudocode,
which is a mixture of code
statements and English phrases. Pseudocode provides enough structure to show
how the code will operate, without getting bogged down in the syntactic details
of a particular programming language or becoming prematurely constrained by
the characteristics of particular programming constructs.
This section discusses two important aspects of program design at the method
level: method decomposition and the implications of passing objects as parameters.
Method Decomposition
Occasionally, a service that an object provides is so complicated that
it cannot reasonably be implemented using one method. Therefore
we sometimes need to decompose a method into multiple methods to
create a more understandable design. As an example, let's examine a
program that translates English sentences into Pig Latin.
Pig Latin is a made-up language in which each word of a sentence
is modified, in general, by moving the initial sound of the word to the end and
adding an “ay” sound. For example, the word
KEY CONCEPT
A complex service provided by an
object can be decomposed to make
use of private support methods.
happy
would be written and pro-
nounced
appyhay
and the word
birthday
would become
irthdaybay
. Words that
begin with vowels simply have a “yay” sound added on the end, turning the word
enough
into
enoughyay
. Consonant blends such as “ch” and “st” at the beginning
of a word are moved to the end together before adding the “ay” sound. Therefore
the word
grapefruit
becomes
apefruitgray.
The
PigLatin
program shown in Listing 7.13 reads one or more sentences,
translating each into Pig Latin.
The workhorse behind the
PigLatin
program is the
PigLatinTranslator
class, shown in Listing 7.14. The
PigLatinTranslator
class provides one fun-
damental service, a static method called
translate
, which accepts a string and
translates it into Pig Latin. Note that the
PigLatinTranslator
class does not
contain a constructor because none is needed.
LISTING 7.13
//********************************************************************
// PigLatin.java Author: Lewis/Loftus
//
// Demonstrates the concept of method decomposition.
//********************************************************************
import
java.util.Scanner;
Search WWH ::
Custom Search