Java Reference
In-Depth Information
338
8.2 Cohesion and Coupling
In this section you will learn two useful criteria for analyzing the quality of the public
interface of a class.
A class should represent a single concept. The public methods and constants that the
public interface exposes should be cohesive. That is, all interface features should be
closely related to the single concept that the class represents.
The public interface of a class is cohesive if all of its features are related to the
concept that the class represents.
If you find that the public interface of a class refers to multiple concepts, then that is a
good sign that it may be time to use separate classes instead. Consider, for example,
the public interface of the CashRegister class in Chapter 4 :
public class CashRegister
{
public void enterPayment(int dollars, int
quarters,
int dimes, int nickels, int pennies)
. . .
public static final double NICKEL_VALUE = 0.05;
public static final double DIME_VALUE = 0.1;
public static final double QUARTER_VALUE = 0.25;
. . .
}
There are really two concepts here: a cash register that holds coins and computes their
total, and the values of individual coins. (For simplicity, we assume that the cash
register only holds coins, not bills. Exercise P8.1 discusses a more general solution.)
It makes sense to have a separate Coin class and have coins responsible for knowing
their values.
public class Coin
{
public Coin(double aValue, String aName) { . . . }
public double getValue() { . . . }
. . .
Search WWH ::




Custom Search