|
|
|
Advertisement
|
Medium cohesion
To increase the method cohesion of the previous CoffeeCup
class, you could divide the functionality performed by
modify() into two methods, add() and
remove():
// In Source Packet in file cohesion/ex2/CoffeeCup.java
// THIS APPROACH WORKS, BUT MAKES THE CODE HARD TO UNDERSTAND
// AND HARD TO CHANGE
public class CoffeeCup {
private int innerCoffee;
public void add(int amount) {
innerCoffee += amount;
}
public int remove(boolean all, int amount) {
int returnValue = 0;
if (all) {
// set innerCoffee to 0
// ignore parameter amount
int allCoffee = innerCoffee;
innerCoffee = 0;
returnValue = allCoffee; // return all coffee
}
else {
// remove the amount of coffee passed as amount
int sip = amount;
if (innerCoffee < amount) {
sip = innerCoffee;
}
innerCoffee -= sip;
returnValue = sip; // return removed amount
}
return returnValue;
}
}
Figure 2: Passing control down to remove().
|
This is a better design, but it's not quite there yet. Although the
add() method does not require you to pass down control,
the remove() method still does. The boolean parameter
all indicates to the remove method whether or
not to remove all coffee (a spill) or to remove some coffee (a sip). In
the case of a sip, the amount parameter indicates the
amount of coffee to remove (the size of the sip). The graphical
depiction of the remove() method, shown in Figure 2, shows
a blackened circle heading down for the all parameter just
as modify() had a blackened circle heading down for the
action parameter. It also includes a parameter,
amount, that is not always used, just as
modify() is not always used. For remove(), if
all is false, amount indicates
the amount of coffee to remove. If all is
true, amount is ignored.
|
Sponsored Links
|