Modern State Pattern Using Enums and Functional Interfaces
Learn more about modern state patterns in this Java post!
Join the DZone community and get the full member experience.
Join For FreeIt's often the case that the behavior of an object should change depending on the objects state. Consider an ShoppingBasket
object. You can add articles to your basket as long the order isn't submitted. But once it's submitted, you typically don't want to be able to change that order anymore. So, there are two states in such a shopping basket object: READONLY
and UPDATEABLE
. Here is the ShoppingBasket
class.
// without state pattern always updateable
public class ShoppingBasket {
private String orderNo;
private List<String> articleNumbers = new ArrayList<>();
public void add(String articleNumber) {
articleNumbers.add(articleNumber);
}
public String getOrderNo() {
return orderNo;
}
public void setOrderNo(String orderNo) {
this.orderNo = orderNo;
}
public void order() {
// some ordering logic and if succeeded, should change state
}
}
In such a class, you can add articles and maybe you can perform an order. Once you've performed an order, the client of such an object would still be able to change that order object, which should not be possible. To prevent clients from updating the order that was already submitted, we want to change the behavior of the ShoppingBasket
. It should not be possible to add articles or change the orderNo
field once the order is submitted. What's an intelligent object-oriented modern Java solution to such a problem? What I usually do in such cases is I use an enum
to implement a GoF state pattern. Here is such an enum
:
public enum UpdateState {
UPDATEABLE(()->Validate.validState(true)), READONLY(()->Validate.validState(false));
private Runnable action;
private UpdateState(Runnable action) {
this.action=action;
}
public <T> T set(T value) {
action.run();
return value;
}
}
My UpdateState
enum takes an Runnable
object as a constructor argument. You can use more complicated functional interfaces to suit specific needs; the sky is your limit in terms of complexity here. But for now, it's an ordinary Runnable
interface. The UpdateState
enum has exactly two states: UPDATEABLE
and READONLY
. The UPDATEABLE
enum value does validate to true, always, and the READONLY
enum value always evaluates to false, which results in an InvalidStateException
(using the Apache Commons Lang Validate
class). The UpdateState
enum has a method called set()
, which takes an argument and returns exactly that given argument. But before returning the argument, the set()
method runs the state-dependent, Runnable
action. Now, why all that hassle?
// shopping basket using modern state pattern
public class ShoppingBasket {
private String orderNo;
private List<String> articleNumbers = new ArrayList<>();
private UpdateState state = UpdateState.UPDATEABLE;
public void add(String articleNumber) {
articleNumbers.add(state.set(articleNumber));
}
public String getOrderNo() {
return orderNo;
}
public void setOrderNo(String orderNo) {
this.orderNo = state.set(orderNo);
}
public void order() {
// some ordering logic and if succeeded, change state
state = UpdateState.READONLY;
}
}
The ShoppingBasket
now has a state field of the enum type UpdateState
. That state field defaults to UPDATEABLE
because when you create the ShoppingBasket,
it's always updateable, meaning that the order wasn't submitted yet. When you fire the order through the order()
method, the state changes to READONLY
. Since the state changed to read-only, the ShoppingBasket
will change its behavior, specifically when clients try to access the class fields. Let's look at the setOrderNo()
method for instance. ThesetOrderNo()
method does not assign the order number directly to the orderNo
field anymore; instead, it calls theUpdateState
enumsset()
method, which returns the given value you want to set. That return value is assigned to your orderNo
field. Theset()
method of the UpdateState
enum always checks whether updates are allowed. So when your ShoppingBasket
s state is UPDATEABLE
, the set()
method will succeed, but when it's READONLY
, then the set()
method of that state will result inIllegalStateException
. This was exactly what we've wanted to achieve in the beginning — make that object read-only if the order is submitted.
Notice that you can make such a state pattern implementation as complex as required. It's a very elegant, short option to drive your object's behavior by objects state. And it saves you a lot if-else typing non-object-oriented logic in all the accessor methods. Consider classes that have 20 fields; you don't want to check state each time in all the methods. That would clearly clutter up your class code. Using the demonstrated state pattern, you save lines of code and your place looks quite tidy. Change the functional interface used in the UpdateState
enum and you'll realize the great potential of state-dependent behavior that can be implemented with very few lines of code.
Opinions expressed by DZone contributors are their own.
Comments