About 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.

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.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.

3 Responses to "Friends Don’t Let Friends Use String States"

  1. Zethiel says:

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

  2. Basanta says:

    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 :)

  3. Brad mongar says:

    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.

Leave a Reply


6 × three =



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close