Java Reference
In-Depth Information
A good structure gives each group clear tasks to complete, avoids giving any
particular person or group too much work, and provides a balance between workers
and management. These guidelines lead to the first of our procedural design
heuristics.
1. Each method should have a coherent set of responsibilities. In our analogy
to a company, each group of employees must have a clear idea of what work it is to
perform. If any of the groups does not have clear responsibilities, it's difficult for the
company director to keep track of who is working on what task. When a new job
comes in, two departments might both try to claim it, or a job might go unclaimed by
any department.
The analogous concept in programming is that each method should have a clear
purpose and set of responsibilities. This characteristic of computer programs is called
cohesion.
Cohesion
A desirable quality in which the responsibilities of a method or process
are closely related to each other.
A good rule of thumb is that you should be able to summarize each of your
methods in a single sentence such as “The purpose of this method is to ....” Writing
a sentence like this is a good way to develop a comment for a method's header. It's
a bad sign when you have trouble describing the method in a single sentence or
when the sentence is long and uses the word “and” several times. Those indications
can mean that the method is too large, too small, or does not perform a cohesive set
of tasks.
The methods of the BadBMI example have poor cohesion. The person method's
purpose is vague, and getWeight is probably too trivial to be its own method. The
reportStatus method would be more readable if the computation of the BMI were
its own method, since the formula is complex.
A subtler application of this first heuristic is that not every method must produce
output. Sometimes a method is more reusable if it simply computes a complex result
and returns it rather than printing the result that was computed. This format leaves the
caller free to choose whether to print the result or to use it to perform further compu-
tations. In the BadBMI program, the reportStatus method both computes and prints
the user's BMI. The program would be more flexible if it had a method to simply
compute and return the BMI value, such as BMIFor in the BMI3 version of the code.
Such a method might seem trivial because its body is just one line in length, but it has
a clear, cohesive purpose: capturing a complex expression that is used several times
in the program.
 
Search WWH ::




Custom Search