The Artima Developer Community
Sponsored Link

What's a Method to Do?
How to Maximize Cohesion While Avoiding Explosion
by Bill Venners
First Published in JavaWorld, April 1998

<<  Page 3 of 9  >>

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;
    }
}

Passing control down to remove()
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.

<<  Page 3 of 9  >>


Sponsored Links



Google
  Web Artima.com   
Copyright © 1996-2017 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us