Learn the state pattern.

Better programmers learn patterns from other programmers.

Learning patterns is something most good programmers do as they gain expertise in software engineering. Once you realize you will gain knowledge faster if you don’t limit yourself to your own experience, you begin to study the wisdom others have acquired over the years. With millions of developers writing code for several decades now, people have learned several techniques that appear time and again. These are known as patterns.

One such technique is the State pattern. This pattern is helpful when an object’s behavior depends on its internal status. In this scenario, an object can be in only one state at any given time. In each given state, the behavior of the object is different. For example, say a car object has states REVERSE, PARKED, and INGEAR. A call to accelerate() will have different behavior depending on its state.

In this pattern, accelerate() is not an actual method in the car object, but rather an interface. Instead, concrete implementations define the method in classes that implement the interface. Another class controls the context, which determines which state the car object is in, and assigns the implementation class.

Each state limits the object’s behavior. So it is possible to have multiple methods in the implementation class if they are associated with that state. For example, maybe displayParkingLights() returns true (or performs other actions) for the PARKED implementation, but not for the other two.

The use of this pattern avoids large monolithic conditional statements. Plus, new states can be added (or an existing state altered) without changing the other states. Separating this behavior based on state also makes the code easier to test.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: