Chapter 8: Designing Classes
New ASMSU Tutor Available
- Steve Aldrich
- saldrich@cs.montana.edu
- 585-1271
Desirable Class Characteristics
- They represent a single concept.
- Often, they are nouns (e.g. Point). Methods are typically verbs.
- They can be actors (e.g. Scanner).
- They can also be a utility class with no objects (e.g. Math).
Definitions
- Cohesion. A class is cohesive if all of its features
are related to the concept that the class represents.
- Coupling. A class that depends on few other classes is
loosely coupled. A class that depends on many other classes
is highly coupled. Low coupling is more desirable.
- Consistency. A class should use a consistent scheme
for names and parameters.
- Immutable Class. An immutable class has only accessor methods.
It has no mutator methods.
Side Effects
- A side effect occurs when a method causes an externally
observable data modification.
- The fewer side effects a method has, the better.
- Access methods are best, then mutator methods.
- Generally try to avoid methods that change an explicit
parameter or that change another object such as System.out
(e.g. most print methods change System.out and should
thus be avoided).
- Tip - do not modify change the contents of parameter values
in a method.
Lecture Code
We used the sample solution for Program 1 below to demonstrate
the above concepts. We also decoupled the GringottsAccount class
from the System.out class by replacing the printAccount method with
to toString method. The TestProgram was updated to use this
new method.