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 5 of 9  >>

Advertisement

Reducing assumptions
Functionally cohesive methods also increase code flexibility because they make fewer assumptions about the order in which particular actions are performed. Here is an example of a method that is not very functionally cohesive because it assumes too much:

// In Source Packet in file cohesion/ex4/CoffeeCup.java
class CoffeeCup {

    private int innerCoffee;
    private int innerCream;
    private int innerSugar;

    private static final int CREAM_FRACTION = 30;
    private static final int SUGAR_FRACTION = 30;

    public void add(int amountOfCoffee) {

        innerCoffee += amountOfCoffee;
        innerCream += amountOfCoffee/CREAM_FRACTION;
        innerSugar += amountOfCoffee/SUGAR_FRACTION;
    }
    //...
}

This CoffeeCup object keeps track not only of the amount of coffee it contains (innerCoffee), but also of the amount of cream (innerCream) and sugar (innerSugar). As you would expect, the add() method accepts an amount of coffee to add, then increments innerCoffee by that amount; however, add() doesn't stop there. It assumes that anyone wishing to add coffee to a cup also would want to add some cream and sugar, in fixed amounts relative to the amount of coffee added. So add() goes ahead and adds the cream and sugar as well.

The design of this method reduces code flexibility because later, if a programmer wanted to add coffee with cream, but no sugar, this method would be of no use. A more flexible design would be:

// In Source Packet in file cohesion/ex5/CoffeeCup.java
class CoffeeCup {

    private int innerCoffee;
    private int innerCream;
    private int innerSugar;

    public void addCoffee(int amount) {
        innerCoffee += amount;
    }

    public void addCream(int amount) {
        innerCream += amount;
    }

    public void addSugar(int amount) {
        innerSugar += amount;
    }
    //...
}

These methods are more functionally cohesive because they each do one thing. This design is more flexible because the programmer can call any of the methods at any time and in any order.

<<  Page 5 of 9  >>


Sponsored Links



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