Guidelines for Class Design

Good design of individual classes is crucial to good overall system design. A well-designed class is more re-usable in different contexts, and more modifiable for future versions of software. Here, we'll look at some general class design guidelines, as well as some tips for specific languages, like C++ or Java.

Reminder: Important C++/Java differences

Remember, there are some differences in the implementations of different object-oriented languages. The primary ones we've seen are C++ and Java.

General goals for building a good class

Designing a good class interface

By interface, we are talking about what the class user (a programmer who uses a specific class in their own coding) sees. This is the public section of the class. When desiging the interface of a class, here are some things to strive for: Sometimes these goals can conflict with each other. Designer must use best judgement to balance any conflicts and decide which aspects are most important.

Some counterexamples


Consider this class
  pulic class Roster
    public addStudent(Student s) { ... }
    public void deleteStudent(Student s)  { ... }
    public Student getStudent(int index) { ... }
    public void processCommand(String cmd) { ... }


Consider the first version of class Fraction I use when introducing classes: Clearly we could add more functions to these -- they were just preliminary examples. In what ways are these class examples incomplete? What should be added as standard features? If arithmetic operations were left out of the Fraction class, would this be a fatal flaw?



Consider the ListIterator interface in Java.


Look at the Java String class

Encapsulation -- separating interface and implementation

General guidelines

The Law of Demeter

Accessors and Mutators

Separation of accessors and mutators

It's usually best to keep accessors and mutators separate -- an accessor should not change the object's state, and mutator should.

There are some classes that do things otherwise. A decision must be made to balance things like clarity against convenience, for example. Consider the java.util.StringTokenizer class.