Designing fields and methods

How to keep fields focused and methods decoupled

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/
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.

For example, if later someone adds a 20 ounce cup to the offerings of the virtual café, it would then be possible to hold up to 592 milliliters (ml) of coffee in a cup. If a programmer adds the new cup size without realizing you are using 500 ml to indicate that a cup needs washing, it is likely that a bug will be introduced. If a customer in your virtual café bought a 20 ounce cup, then took a big 92-ml gulp, he or she would then have exactly 500 ml remaining in the cup. The customer would be shocked and dissatisfied when, after drinking only 92 ml, the cup disappeared from his or her hand and appeared in the sink, ready to be washed. And, even if the programmer making the change realized that you were using a special value, another special value for the unwashed attribute would have to be chosen.

A better approach to this situation is to have a separate field to model the separate attribute:

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

Here the innerCoffee field is used only to model the amount of coffee in the cup attribute. The cup-needs-washing attribute is modeled by the needsWashing field. This scheme is more easily understood than the previous scheme, which used a special value of innerCoffee and wouldn't prevent someone from expanding the maximum value for innerCoffee.

Using constants

Another rule of thumb to follow when creating fields is to use constants (static final variables) for constant values that are passed to, returned from, or used within methods. If a method expects one of a finite set of constant values in one of its parameters, defining constants helps make it more obvious to client programmers what needs to be passed in that parameter. Likewise, if a method returns one of a finite set of values, declaring constants makes it more obvious to client programmers what to expect as output. For example, it is easier to understand this:

if (cup.getSize() == CoffeeCup.TALL) {

than it is to understand this:

if (cup.getSize() == 1) {

You should also define constants for internal use by the methods of a class -- even if those constants aren't used outside the class -- so they are easier to understand and change. Using constants makes code more flexible. If you realize you miscalculated a value and you didn't use a constant, you'll have to go through your code and change every occurrence of the hard-coded value. If you did use a constant, however, you'll only need to change it where it is defined as a constant.

Constants and the Java compiler

A useful thing to know about the Java compiler is that it treats static final fields (constants) differently than other kinds of fields. References to static final variables initialized to a compile-time constant are resolved at compile-time to a local copy of the constant value. This is true for constants of all the primitive types and of type java.lang.String.

Normally, when your class refers to another class -- say, class java.lang.Math -- the Java compiler places symbolic references to class Math into the class file for your class. For example, if a method of your class invokes Math.sin(), your class file will contain two symbolic references to Math:

To execute the code contained in your class that refers to Math.sin(), the JVM would need to load class Math to resolve the symbolic references.

If, on the other hand, your code only referred to the static final class variable PI declared in class Math, the Java compiler would not place any symbolic reference to Math in the class file for your class. Instead, it would simply place a copy of the literal value of Math.PI into your class's class file. To execute the code contained in your class that uses the Math.PI constant, the JVM would not need to load class Math.

The upshot of this feature of the Java compiler is that the JVM doesn't have to work any harder to use constants than it does to use literals. Preferring constants over literals is one of the few design guidelines that enhances program flexibility without risking any degradation of program performance.

Three kinds of methods

The remainder of this article will discuss method design techniques that are concerned with the data a method uses or modifies. In this context, I'd like to identify and name three basic types of methods in Java programs: the utility method the state-view method, and the state-change method.

The utility method

A utility method is a class method that doesn't use or modify the state (class variables) of its class. This kind of method simply provides a useful service related to its class of object.

Some examples of utility methods from the Java API are:

The state-view method

A state-view method is a class or instance method that returns some view of the internal state of the class or object, without changing that state. (This kind of method brazenly disregards the Heisenberg Uncertainty Principle -- see Resources if you need a refresher on this principle.) A state-view method may simply return the value of a class or instance variable, or it may return a value calculated from several class or instance variables.

Some examples of state-view methods from the Java API are:

  • (In class Object) public String toString() -- returns a string representation of the object
  • (In class Integer) public byte byteValue() -- returns the value of the Integer object as a byte
  • (In class String) public int indexOf(int ch) -- returns the index within the string of the first occurrence of the specified character

The state-change method

The state-change method is a method that may transform the state of the class in which the method is declared, or, if an instance method, the object upon which it is invoked. When a state-change method is invoked, it represents an "event" to a class or object. The code of the method "handles" the event, potentially changing the state of the class or object.

Some examples of state-change methods from the Java API are:

  • (In class StringBuffer) public StringBuffer append(int i) -- appends the string representation of the int argument to the StringBuffer
  • (In class Hashtable) public synchronized void clear() -- clears the Hashtable so that it contains no keys
  • (In class Vector) public final synchronized void addElement(Object obj) -- adds the specified component to the end of the Vector, increasing its size by one

Minimizing method coupling

Armed with these definitions of utility, state-view, and state-change methods, you are ready for the discussion of method coupling.

As you design methods, one of your goals should be to minimize coupling -- the degree of interdependence between a method and its environment (other methods, objects, and classes). The less coupling there is between a method and its environment, the more independent that method is, and the more flexible the design is.

Methods as data transformers

To understand coupling, it helps to think of methods purely as transformers of data. Methods accept data as input, perform operations on that data, and generate data as output. A method's degree of coupling is determined primarily by where it gets its input data and where it puts its output data.

Figure 1 shows a graphical depiction of the method as data transformer: A data flow diagram from structured (not object-oriented) design.

Figure 1. The method as data transformer

Input and output

A method in Java can get input data from many sources:

  • It can require that the caller specify its input data as parameters when it is invoked
  • It can grab data from any accessible class variables, such as the class's own class variables or any accessible class variables of another class
  • If it is an instance method, it can grab instance variables from the object upon which it was invoked

Likewise, a method can express its output in many places:

  • It can return a value, either a primitive type or an object reference
  • It can alter objects referred to by references passed in as parameters
  • It can alter any class variables of its own class or any accessible class variables of another class
  • If it is an instance method, it can alter any instance variables of the object upon which it was invoked
  • It can throw an exception

Note that parameters, return values, and thrown exceptions are not the only kinds of method inputs and outputs mentioned in the above lists. Instance and class variables also are treated as input and output. This may seem non-intuitive from an object-oriented perspective, because access to instance and class variables in Java is "automatic" (you don't have to pass anything explicitly to the method). When attempting to gauge a method's coupling, however, you must look at the kind and amount of data used and modified by the code, regardless of whether or not the code's access to that data was "automatic."

Minimally coupled utility methods

The least coupled method that is possible in Java is a utility method that:

  1. Takes input only from its parameters
  2. Expresses its output only through its parameters or its return value (or by throwing an exception)
  3. Accepts as input only data that is actually needed by the method
  4. Returns as output only data that is actually produced by the method

A good utility method

For example, the method convertOzToMl() shown below accepts an int as its only input and returns an int as its only output:

1 2 3 Page 1
Page 1 of 3