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

Page 5 of 5

This style of programming yields code that is difficult to change because changes can have unforeseen side-effects. In this example, the convertOzToMl() method has a high degree of coupling. It is coupled to two classes, FlyingSaucer and PurpleZebra, which are required for passing data to and from the method. In Figure 4, you can see a graphical depiction of this kind of programming:

Figure 4. Please don't put spaghetti in your computer

Minimally coupled state-view methods

A minimally coupled state-view method:

  • Uses as input only parameters and the class variables of the class that declares method, plus (if an instance method) the instance variables of the object upon which the method is invoked
  • Expresses its output only through its return value, parameters, by throwing an exception


The input rule could alternatively be put like this: The input to a minimally coupled state-view method can come from anywhere except directly from non-constant class variables declared in other classes.

The isReadyForNextUse() method of the CoffeeCup class shown previously in this article is an example of a minimally coupled state-view method. This method takes input only from the needsWashing instance variable and expresses output only through its return value.

Figure 5 shows a graphical depiction of isReadyForNextUse().

Figure 5. A minimally coupled state-view method

Minimally coupled state-change methods

A minimally coupled state-change method:

  • Uses as input only parameters and the class variables of the class that declares the method, plus (if an instance method) the instance variables of the object upon which the method is invoked
  • Expresses its output only through its return value, parameters, by throwing an exception, through the class variables of the class that declares the method, or (if an instance method) through the instance variables of the object upon which the method is invoked


The input requirements of a minimally coupled state-change method are just like those of a minimally coupled state-view method: the input can come from anywhere except directly from non-constant class variables declared in other classes. Similarly, the output of a minimally coupled state-change method can be expressed in any fashion except by directly modifying data declared as or referenced from class variables declared in other classes.

The add() method of the CoffeeCup class shown below is an example of a minimally coupled state-change method:

// In source packet in file coupling/ex5/CoffeeCup.java
class CoffeeCup {
    private int innerCoffee;
    public void add(int amount) {
        innerCoffee += amount;
    }
    //...
}


The add() method takes as input one parameter, amount, and one instance variable, innerCoffee. It expresses its output by changing the innerCoffee instance variable. Figure 6 shows a graphical depiction of the add() method.

Figure 6. An instance method of the CoffeeCup class

The hidden this reference
Note that in Figure 5, the needsWashing instance variable is shown as input to the isReadyForNextUse() method. In Figure 6, the innerCoffee instance variable is shown being passed down as input and passed back as output. Although the purpose of treating instance variables as input and output to methods is to help you visualize method coupling, this treatment is also representative of how instance methods work in the Java virtual machine.

Instance methods are able to access instance variables because the methods receive a hidden this reference as their first parameter. The Java compiler inserts a reference to this at the beginning of the parameter list for every instance method it compiles. Because an instance method receives a reference to the instance variables, those instance variables can serve as input, output, or both. A hidden this reference is not passed to class methods, which is why you don't need an instance to invoke them and why they can't access any instance variables.

Conclusion

This article covered some very fundamental territory, which can be summarized as three guidelines:

  1. The especially valuable guideline for fields
    Don't assign a special meaning to special values of a field in an effort to represent multiple attributes with the single field. Instead, use a separate field to represent each separate attribute of a class or object.

  2. The constant corollary
    Prefer constants (static final fields) over hard-coded literals (1.5, "Hi there!"), especially if you need to use the same constant value in multiple places.

  3. The minimize-coupling mantra
    Always strive to minimize the coupling of methods: Take as input only data needed by the method; express as output only data produced by the method.


Next month

In next month's Design Techniques I'll continue the mini-series of articles that focus on designing classes and objects. Next month's article, the third of this mini-series, will discuss cohesion, the degree of relatedness between the various functions performed within a method body.

I imagine that some readers will find they already know all about the guidelines presented in this and next month's articles. I hope that such readers will forgive me for being obvious and bear with me while I get through the basics. As I said at the start, I think it's important to reiterate the basics from time to time. After next month's article, I'll be writing about design guidelines that are more specific to Java.

A request for reader participation

Software design is subjective. Your idea of a well-designed program may be your colleague's maintenance nightmare. In light of this fact, I am trying to make this column as interactive as possible.

I encourage your comments, criticisms, suggestions, flames -- all kinds of feedback -- about the material presented in this column. If you disagree with something, or have something to add, please let me know.

You can either enter a comment via the form at the bottom of the article, e-mail me directly (see the e-mail link in my bio below), or participate in a discussion forum devoted to this material.

About the author

Bill Venners has been writing software professionally for 12 years. Based in Silicon Valley, he provides software consulting and training services under the name Artima Software Company. Over the years he has developed software for the consumer electronics, education, semiconductor, and life insurance industries. He has programmed in many languages on many platforms: assembly language on various microprocessors, C on Unix, C++ on Windows, Java on the Web. He is author of the book: Inside the Java Virtual Machine, published by McGraw-Hill. The small print: "Designing Fields and Methods" Article Copyright (c) 1998 Bill Venners. All rights reserved.
  • 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