Java Reference
In-Depth Information
The
BadBMI
program suffers heavily from chaining. Each method does a small
amount of work and then calls the next method, passing more and more parameters
down the chain. The
main
method calls
person
, which calls
getWeight
, which calls
reportStatus
. Never does the flow of execution return to
main
in the middle of the
computation. So when you read
main
, you don't get a very clear idea of what compu-
tations will be made.
One method should not call another simply as a way of moving on to the next
task. A more desirable flow of control is to let
main
manage the overall execution of
tasks in the program, as shown in the
BMI3
program and on the right side of Figure
4.8. This guideline doesn't mean that it is always bad for one method to call another
method; it is okay for one method to call another when the second is a subtask within
the overall task of the first, such as in
BMI3
when the
reportResults
method calls
reportStatus
.
5. Data should be “owned” at the lowest level possible.
Decisions in a com-
pany should be made at the lowest possible level in the organizational hierarchy. For
example, a low-level administrator can decide how to perform his or her own work
without needing to constantly consult a manager for approval. But the administrator
does not have enough information or expertise to design the entire product line; this
design task goes to a higher authority such as the manager. The key principle is that
each work task should be given to the lowest person in the hierarchy who can cor-
rectly handle it.
This principle has two applications in computer programs. The first is that the
main
method should avoid performing low-level tasks as much as possible. For
example, in an interactive program
main
should not read the majority of the user
input or contain lots of
println
statements.
The second application is that variables should be declared and initialized in the
narrowest possible scope. A poor design is for
main
(or another high-level method) to
read all of the input, perform heavy computations, and then pass the resulting data as
parameters to the various low-level methods. A better design uses low-level methods
to read and process the data, and return data to
main
only if they are needed by a later
subtask in the program.
It is a sign of poor data ownership when the same parameter must be passed down
several method calls, such as the
height
variable in the
BadBMI
program. If you are
passing the same parameter down several levels of calls, perhaps that piece of data
should instead be read and initialized by one of the lower-level methods (unless it is a
shared object such as a
Scanner
).
Search WWH ::
Custom Search