Newsletter sign-up
View all newsletters

Enterprise Java Newsletter
Stay up to date on the latest tutorials and Java community news posted on JavaWorld

Sponsored Links

Optimize with a SATA RAID Storage Solution
Range of capacities as low as $1250 per TB. Ideal if you currently rely on servers/disks/JBODs

Designing fields and methods

How to keep fields focused and methods decoupled

  • Print
  • Feedback
This month's installment of Design Techniques is the second in a mini-series of columns about designing objects. In last month's column, which covered designing objects for proper initialization, I talked about how to design constructors and initializers. This month and next month I'll discuss design principles for the actual fields and methods of the class. After that, I'll write about finalizers and show how to design objects for proper cleanup at the end of their lives.

The material for this article (avoiding special data values, using constants, minimizing coupling) and the next article (maximizing cohesion) may be familiar to many readers, as the material is based on general design principles that are quite independent of the Java programming language. Nevertheless, because I have encountered so much code over the years that doesn't take advantage of these principles, I think they deserve to be restated from time to time. In addition, in this article I attempt to show how these general principles apply to the Java language in particular.

Designing fields

In designing fields, the main rule of thumb is to avoid using one variable to represent multiple attributes of a class. You can violate this rule by denoting special values within a variable, each with its own special meaning.

As used here, an attribute is a distinguishing characteristic of an object or class. Two attributes of a CoffeeCup object, for example, could be:

  • The amount of coffee the cup contains
  • Whether the cup is clean or dirty


To take a closer look at this rule, imagine you are designing a CoffeeCup class for the virtual café described in last month's Design Techniques column. Assume you want to model whether or not a coffee cup in your virtual café has been washed and is ready for use by the next customer. With this information on hand, you can ensure that you don't reuse a coffee cup before it has been washed.

If you decide you only care whether or not a cup has been washed if it is empty, you could use a special value of the innerCoffee field, which normally is used to keep track of the amount of coffee in the cup, to represent an unwashed cup. If 473 milliliters (16 fluid ounces) is the maximum amount of coffee in your largest cup, then the maximum value of innerCoffee normally would be 473. Thus, you could use an innerCoffee value of, say, 500 (a special value) to indicate an empty cup that is unwashed:

// In source packet in file fields/ex1/CoffeeCup.java
class CoffeeCup {
    private int innerCoffee;
    public boolean isReadyForNextUse() {
        // If coffee cup isn't washed, then it's
        // not ready for next use
        if (innerCoffee == 500) {
            return false;
        }
        return true;
    }
    public void setCustomerDone() {
        innerCoffee = 500;
        //...
    }
    public void wash() {
        innerCoffee = 0;
        //...
    }
    // ...
}


This code will give CoffeeCup objects the desired behavior. The trouble with this approach is that special values aren't readily understood, and they make code harder to change. Even if you describe special values in a comment, it may take other programmers longer to understand what your code is doing. Moreover, they may never understand your code. They may use your class incorrectly or change it such that they introduce a bug.

  • Print
  • Feedback

Resources
  • The Heisenberg Uncertainty Principle states that we can't know both the position and the momentum of elementary particles, because the act of measuring one of these values changes the other. Put another way, if elementary particles were objects, they wouldn't have any state-view methods, because you couldn't determine their state (in this case, position and momentum) without changing that state.
  • Recommended books on Java Design http://www.artima.com/designtechniques/booklist.html
  • Source packet that contains the example code used in this article http://www.artima.com/flexiblejava/coupling.html
  • The discussion forum devoted to the material presented in this article. http://www.artima.com/flexiblejava/fjf/fieldsmethods/index.html
  • Object Orientation FAQ http://www.cyberdyne-object-sys.com/oofaq/
  • 7237 Links on Object Orientation http://www.rhein-neckar.de/~cetus/software.html
  • The Object-Oriented Page http://www.well.com/user/ritchie/oo.html
  • Collection of information on OO approach http://arkhp1.kek.jp:80/managers/computing/activities/OO_CollectInfor/OO_CollectInfo.html
  • Design Patterns Home Page http://hillside.net/patterns/patterns.html
  • A Comparison of OOA and OOD Methods http://www.iconcomp.com/papers/comp/comp_1.html
  • Object-Oriented Analysis and Design MethodsA Comparative Review http://wwwis.cs.utwente.nl:8080/dmrg/OODOC/oodoc/oo.html
  • Patterns discussion FAQ http://gee.cs.oswego.edu/dl/pd-FAQ/pd-FAQ.html
  • Implementing Basic Design Patterns in Java (Doug Lea) http://g.oswego.edu/dl/pats/ifc.html
  • Patterns in Java AWT http://mordor.cs.hut.fi/tik-76.278/group6/awtpat.html
  • Software Technology's Design Patterns Page http://www.sw-technologies.com/dpattern/
  • Synchronization of Java Threads Using Rendezvous http://www-cad.eecs.berkeley.edu/~jimy/classes/rendezvous/
  • Design PatternsElements of Reusable Object-Oriented Software, In Java http://www.zeh.com/local/jfd/dp/design_patterns.html
  • Another example of obvious content from Bill Venners http://www.artima.com/bv/music/obvioussong.html