Strategy State

Friends Don’t Let Friends Use String States

by on July 8, 2013 10:40 am

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, asktheteam@keyholesoftware.com

  • Share:

5 Responses to “Friends Don’t Let Friends Use String States”

  1. Phil says:

    In .NET, they handle enums a little differently (they’re basically labels for ints instead of strings), and I quit using them long ago in favor of the Strategy State for exactly these reasons.

    In fact, I tend to use Strategy State for anything I might normally use an enum for (including a list of the United States – equivocation ftw!) unless I am 99.9% sure I will never need those items to be anything other than a single value representation.

    • Brad Mongar says:

      Phil, good contrast with .NET. I am mostly a Java guy so I was unaware of the differences in the enum implementation. I do like that the Java enum allows for full class implementations of individual enum instances. They can even each be a different classes not just individually initialized instances of the same class. It makes the Java enum a great way to implement Strategy States. I look forward to learning more about .NET and C# and a bit disappointed to hear the enums aren’t as powerful.

  2. Frisian says:

    Good example, so I have finally a bookmark for those developers, who spill enum comparisons all over the place :-)
    Given your example, I would even go further: First, add dedicated methods open(), close(), cancel() and ship() alike reOpen(). setOrderState() should be private and be called by the aforementioned methods.
    Second, the enum can be extended to be a finite state machine, so the Order class just calls something like getOrderState().next(newState). With an interface one can even switch the FSM for different kind of orders. The BabyState example in http://cyrille.martraire.com/2012/08/java-enums-you-have-grace-elegance-and-power-and-this-is-what-i-love/ is a good demonstration.
    Two minor things: The condition in line 23 of the final example should be negated and there should be an initial orderState value.

    • Brad Mongar says:

      Frisian, thanks for your feedback. I fixed the not condition – thanks for pointing that out. You are right that hiding the set state and having business operations set the state would be a better implementation. I was just trying to keep the example simple. :)

Leave a Reply

Things Twitter is Talking About
  • Famo.us' main idea is for HTML5/JS/CSS web pages to feel like native mobile apps. So, @zachagardner tried it out - http://t.co/S77TSKHDKd
    April 15, 2014 at 6:40 PM
  • @JKFeldkamp Thanks for your RT! Such a neat technology. We're so excited @zachagardner is getting involved. Have a great day!
    April 15, 2014 at 4:00 PM
  • .@zachagardner has been tinkering with Famo.us (@befamous) released 4/10. What he's learned so far with a POC app - http://t.co/1jMqBfZURn
    April 15, 2014 at 2:29 PM
  • Tutorial: create #RabbitMQ Template to send msg to an exchange & listen for msgs with a routing key pattern - http://t.co/qDbq6TrxtW
    April 11, 2014 at 10:02 AM
  • There's a great #KC conference coming up on April 23rd - @KCITP's Mobile Midwest http://t.co/CuQGby6kvD Shift into a “Mobile First” mindset!
    April 10, 2014 at 3:59 PM
  • Interesting - 6 #programming paradigms that change how u think about coding: http://t.co/QpRdx76Sn2 & its discussion: http://t.co/DVBRstecba
    April 10, 2014 at 10:11 AM
  • DYK? When we share/RT/blog/etc, it doesn't mean that Keyhole endorses it - we just like variety of opinions! Info: http://t.co/MXhB9lE9tV
    April 9, 2014 at 2:13 PM
  • Developers, need a chuckle? 12 Problems Only Programmers Understand - http://t.co/8PxJSYg0FA #funny
    April 9, 2014 at 2:00 PM
  • Immediately looking to add to our team a Sr. C# developer with knowledge of #NodeJS, #Marionette & #MongoDB. Details: http://t.co/Yyq0b6iza3
    April 9, 2014 at 1:27 PM
  • A huge welcome to Vince Pendergrass who joins the Keyhole team this week!
    April 8, 2014 at 2:37 PM
  • We have 5 Keyhole folks with birthdays this week! Happy birthdays to @Judyj5, @zachagardner, @bmongar, @brianletteri & Mark D!
    April 8, 2014 at 12:22 PM
  • RT @tomonezero: #MongoDB 2.6 is out – Our Biggest Release Ever http://t.co/7iIDYU3CKF
    April 8, 2014 at 9:02 AM
  • @kcjobseekers Thank you for the RT! Have a fantastic day.
    April 7, 2014 at 2:16 PM
  • Immediately looking to add to our team a Sr. C# developer with knowledge of #NodeJS, #Marionette, #MongoDB. Details - http://t.co/Yyq0b6iza3
    April 7, 2014 at 2:10 PM
  • Need to get up-to-speed fast? We train dev teams. Here's one of our newest courses covering UI dev with #AngularJS: http://t.co/Bf3UuClj4Z
    April 7, 2014 at 9:20 AM
  • “Any fool can write code that a computer can understand. Good programmers write code that humans can understand.” - Martin Fowler
    April 4, 2014 at 11:36 AM
  • No better cure for IT stress than friendly humor. Here are 6 funny moments from Keith Shakib's development career - http://t.co/m7qX9q98EB
    April 4, 2014 at 10:21 AM
  • This could come in handy - 75 Essential Cheat Sheets for Designers & Programmers: http://t.co/ST9YnSqdHD #HTML5 #Java #JavaScript #SQL etc.
    April 3, 2014 at 4:43 PM
  • No better cure for stress than friendly humor. Use itwisely & it can be one of your most important #softskills - http://t.co/m7qX9q98EB
    April 3, 2014 at 10:32 AM
  • Keith's favorite #funny line of all time came from one of the most kind & loveable programmers he has ever met - http://t.co/m7qX9q98EB
    April 2, 2014 at 2:25 PM