Friends Don’t Let Friends Use String States

Brad Mongar Programming 5 Comments

Attention: The following article was published over 11 years ago, and the information provided may be aged or outdated. Please keep that in mind as you read the post.

Many of my coworkers have covered exciting new technologies and frameworks to aid your programming expertise. But at this time I think it is important to reach back and cover an important programming basic. Throughout my programming career one of the most common anti-patterns I have seen is the “String State.” It has appeared in some form or another in every project I have worked on.

Simply put, the String State anti-pattern is the use of a Java String to represent the state of an object.

Sure, string representations of states are important. You want the code to be readable, you want a readable value in the database for reports, and you want a user-readable representation of the state to present on your interface. All of these are good things and you should have some string representation of your state — but don’t let string be the entire implementation of your state.

Take for example this simplified version of a shopping cart:

package stringstate;

public class Item {
	private String name;
	private int price;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getPrice() {
		return price;
	}
	public void setPrice(int price) {
		this.price = price;
	}
}

package stringstate;

public interface OrderState {
	public static String OPEN = "Open";
	public static String CLOSED = "Closed";
}

package stringstate;

import java.util.ArrayList;
import java.util.List;

public class Order implements OrderState {
	private List items = new ArrayList();
	private String orderState;

	public List getItems() {
		return items;
	}

	protected  void setItems(List items) {
		this.items = items;
	}

	public String getOrderState() {
		return orderState;
	}

	public void setOrderState(String orderState) {
		this.orderState = orderState;
	}

	public void addItem(Item anItem){
		getItems().add(anItem);
	}

}

In this example the state is used for no business logic. In this case a string state would not be harmful. However no project is this simple. Even if a state starts out as display/store only, you will eventually use it for business logic. Trust me – if the state of an object is important enough to store, then eventually you will have to make decisions with it.

So now your oversimplified shopping cart needs to prevent people from adding items if it is closed. Easy: add a new method and modify addItem.

public void addItem(Item anItem){
		if (canModify()){
			getItems().add(anItem);
		} else {
			throw new IllegalStateException("Cannot add items to a closed order");
		}
	}

	public boolean canModify(){
		return getOrderState().equals(OPEN);
	}

So far not that bad.

Why am I so down on string states you ask? Because now you want to add 2 new states New and Finalized, as well as give the user the option to reopen a non-finalized order. Sure, a new method, a modification to canModify, a check on setOrderState and we are on our way.

But wait, now the user wants 2 Finalized states: Shipped and Canceled. Just a few more tweaks, right?

Now your order code is riddled with “if statements” having to do with states:

package stringstate;

import java.util.ArrayList;
import java.util.List;

public class Order implements OrderState {
	private List items = new ArrayList();
	private String orderState;

	public List getItems() {
		return items;
	}

	protected  void setItems(List items) {
		this.items = items;
	}

	public String getOrderState() {
		return orderState;
	}

	public void setOrderState(String orderState) {
		if (!isFinalized()){
			this.orderState = orderState;
		}
	}

	public void addItem(Item anItem){
		if (canModify()){
			getItems().add(anItem);
		} else {
			throw new IllegalStateException("Cannot add items to a closed order");
		}
	}

	public boolean canModify(){
		return getOrderState().equals(OPEN);
	}

	public void reOpen(){
		if (!isFinalized()){
			setOrderState(OPEN);
		}
	}

	public boolean isFinalized(){
		return getOrderState().equals(SHIPPED) || getOrderState().equals(CANCELED);
	}
}

Oops, we forgot to add the new state to canModify().

Now take the example of a Strategy State in which all the state logic is delegated to an object smarter than a string.

The first benefit is to make all the logic in the order about the order, and not about the order state. The next benefit is anytime you add a new decision based on state, you can implement it abstractly to force implementation in all the states or to provide a default implementation.

Order:

package strategystate;

import java.util.ArrayList;
import java.util.List;

public class Order {
	private List items = new ArrayList();
	private OrderState orderState;

	public List getItems() {
		return items;
	}

	protected  void setItems(List items) {
		this.items = items;
	}

	public OrderState getOrderState() {
		return orderState;
	}

	public void setOrderState(OrderState orderState) {
		if (!getOrderState().isFinalized()){
			this.orderState = orderState;
		}
	}

	public void addItem(Item anItem){
		if (getOrderState().canModify()){
			getItems().add(anItem);
		} else {
			throw new IllegalStateException("Cannot add items to a closed order");
		}
	}

	public void reOpen(){
		if (!getOrderState().isFinalized()){
			setOrderState(OrderState.OPEN);
		}
	}

}

public enum OrderState {
	NEW("New",true,false),
	OPEN("Open",true,false),
	CLOSED("Closed",false,false),
	SHIPPED("Shipped",false,true),
	CANCELED("Canceled",false,true);

	protected String name;
	protected boolean finalized;
	protected boolean modify;

	private OrderState(String name, boolean canModify, boolean isFinalized){
		this.name = name;
		this.finalized= isFinalized;
		this.modify = canModify;
	}
	public boolean canModify(){
		return modify;
	}
	public boolean isFinalized(){
		return finalized;
	}
	public String getName(){
		return name;
	}
}

The more states and more logic you have based on state, the more benefit you have from a strategy state. The Strategy State keeps your main business objects free from growing “if statements” based on lists of states. Plus, you get to keep all the conveniences of the string.

The difference may be small in this example but as the complexity of the domain grows, so does the benefit of the strategy state. Plus, what project have you ever worked on where the complexity didn’t grow? My recommendation is to always start with a strategy state. The overhead is small and you will thank yourself when the project complexity grows.

— Brad Mongar, [email protected]

0 0 votes
Article Rating
Subscribe
Notify of
guest

5 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments