Software Development

Friends Don’t Let Friends Use String States

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 extends Item 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 extends Item 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.
 

Reference: Friends Don’t Let Friends Use String States from our JCG partner Brad Mongar at the Keyhole Software blog.

Keyhole Software

Keyhole is a midwest-based consulting firm with a tight-knit technical team. We work primarily with Java, JavaScript and .NET technologies, specializing in application development. We love the challenge that comes in consulting and blog often regarding some of the technical situations and technologies we face.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

3 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Zethiel
Zethiel
10 years ago

Interface with strings, an Order that had a list of item and also extends from Item, crazy stuff.

Basanta
Basanta
10 years ago

What will be the case if we need to manage the state dynamically, meaning the number of states changes per project ? We are using database table for that though. Additionally, how can we check multiple state condition for an action at same time ? Any help will be helpful :)

Brad mongar
Brad mongar
10 years ago

The extends item was a mistake. I didn’t check the auto fill box in Eclipse’s new class feature. The interface of strings is a pattern for use of static finals in java. Allows scoped usage without a prefix.

Back to top button