Java Reference
In-Depth Information
None of the methods in the
BadBMI
program returns a value. Each method passes
parameters to the next methods, but none of them returns the value. This is a lost
opportunity because several values (such as the user's height, width, or BMI) would
be better handled as
return
values.
4. The
main
method should be a concise summary of the overall program.
The
top person in each major group or department of our hypothetical company reports to
the group's director. If you look at the groups that are directly connected to the direc-
tor at the top level of the company diagram, you can see a summary of the overall
work: design, engineering, and marketing. This structure helps the director stay
aware of what each group is doing. Looking at the top-level structure can also help
the employees get a quick overview of the company's goals.
A program's
main
method is like the director in that it begins the overall task and
executes the various subtasks. A
main
method should read as a summary of the over-
all program's behavior. Programmers can understand each other's code by looking at
main
to get a sense of what the program is doing as a whole.
A common mistake that prevents
main
from being a good program summary is the
inclusion of a “do-everything” method. When the
main
method calls it, the do-everything
method proceeds to do most or all of the real work.
Another mistake is setting up a program in such a way that it suffers from
chaining
.
Chaining
An undesirable design in which a “chain” of several methods call each
other without returning the overall flow of control to
main
.
A program suffers from chaining if the end of each method simply calls the
next method. Chaining often occurs when a new programmer does not fully under-
stand returns and tries to avoid using them by passing more and more parameters
down to the rest of the program. Figure 4.8 shows a hypothetical program with
two designs. The flow of calls in a badly chained program might look like the dia-
gram on the left.
main
main
method1
method2
method3
method4
method5
method1
method2
method3
method4
method5
Figure 4.8
Sample code with chaining (left) and without chaining (right)
Search WWH ::
Custom Search