Recommended: Sing it, brah! 5 fabulous songs for developers
JW's Top 5
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
Page 2 of 5
public class TrafficLight {
public static final int RED = 0;
public static final int YELLOW = 1;
public static final int GREEN = 2;
private int currentColor = RED;
public int change() {
switch (currentColor) {
case RED:
currentColor = GREEN;
break;
case YELLOW:
currentColor = RED;
break;
case GREEN:
currentColor = YELLOW;
break;
}
return currentColor;
}
public int getCurrentColor() {
return currentColor;
}
}
In class TrafficLight, the state of the object is stored in the currentColor private instance variable. A "change" event is sent to the object by invoking its public instance method, change(). State changes are accomplished through the execution of the code that implements the change() method.
As you can see from the TrafficLight example, Java objects map to finite state machines in the following ways:
Most objects you design will have many more states than a TrafficLight object. Some objects will have instance variables whose ranges are limited only by available resources, such as memory, rendering
objects that are practically "infinite state machines." But in general, it is helpful to think of objects as state machines
and to design them accordingly.
The TrafficLight class is an example of the generally accepted form of a basic object design. The object has state, represented by instance
variables that are private. The only way that code defined in other classes can affect the object's state is by invoking the
object's instance methods.
Because other classes don't have direct access to the currentColor variable, they can't screw up its value, such as by setting it equal to 5. (In this case, the only valid values for currentColor are 0, 1, and 2.) In addition, there is no way for a TrafficLight object to go directly from state YELLOW to state GREEN, GREEN to RED, or RED to YELLOW.
Given this design of class TrafficLight, a TrafficLight object will always have a valid state and will always experience valid state transitions -- from the beginning of its lifetime
to the end.
Why should you care about designing good objects? One reason is that a set of robust objects can help contribute to the overall robustness of the program they constitute. In addition, well designed objects are more flexible (easier to understand and easier to change) than poorly designed objects.
A fundamental way to make your object designs robust and flexible is by ensuring that your objects have a valid state, and experience only valid state transitions, from the beginning of their lifetimes to the end. The rest of this article will discuss ways to ensure that classes begin their lifetimes with a valid state.