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
  • Have a happy & safe holiday weekend!
    August 29, 2014 at 3:55 PM
  • Useful #JAXB primer that illustrates the power from tools & frameworks that unobtrusively interact with POJOs - http://t.co/J1s5DpcsCp
    August 29, 2014 at 3:19 PM
  • The Keyhole team fantasy football league begins! Huge thanks to our commissioner @zachagardner. Good luck to all in the virtual gridiron!
    August 28, 2014 at 5:30 PM
  • Shout out to last year's winner of our Keyhole #fantasyfootball league - Adi Rosenblum (@adidas28). Will his reign continue? :-)
    August 28, 2014 at 5:30 PM
  • @dashaun That is the perfect way to put it - we are very excited! Great to meet you officially.
    August 28, 2014 at 4:53 PM
  • Check out a quick intro to Functional Reactive Programing and #JavaScript - http://t.co/4LSt6aPJvG #FRP http://t.co/m6G1Kqbwyi
    August 28, 2014 at 4:06 PM
  • When you pair #JAXB & #JPA, you can expect some "gotchas." Here are techniques to help you overcome the hurdles - http://t.co/J1s5DpcsCp
    August 27, 2014 at 1:56 PM
  • Interesting perspective - Famo.us talks big, but jQuery Foundation isn't worried: http://t.co/o9lLpPoh2G Thoughts?
    August 27, 2014 at 12:41 PM
  • We are delighted to say that RJ (@RJvXP) & Donna (@dkbdevlab) join Keyhole today. Welcome to the team!
    August 27, 2014 at 9:22 AM
  • RT @codeproject: Learning MVC - Part 5 Repository Pattern in MVC3 Application with Entity Framework by Akhil Mittal http://t.co/z603gpAH…
    August 27, 2014 at 9:15 AM
  • Know a bright new grad looking to learn? We're seeking a team member on our business side of the Keyhole house - http://t.co/GDvFVmoMF9
    August 26, 2014 at 3:29 PM
  • When you pair #JAXB & #JPA, you can expect to encounter some "gotchas." Techniques & learning to overcome hurdles - http://t.co/J1s5DpcsCp
    August 26, 2014 at 11:12 AM
  • Don't miss Mark Adelsberger's newest post on the Keyhole blog: #JAXB – A Newcomer’s Perspective, Part 2 http://t.co/J1s5DpcsCp
    August 25, 2014 at 1:21 PM
  • A huge welcome to Mike Schlatter who joins the KHS team today!
    August 25, 2014 at 12:33 PM
  • Never used JAXB? Check out a simple usage pattern that pairs #JAXB’s data binding capabilities with JPA - http://t.co/Ki9G04pLR6
    August 22, 2014 at 8:35 AM
  • Check out a quick intro to Functional Reactive Programing and #JavaScript - http://t.co/YGSsz5eynl #FRP http://t.co/m6G1Kqbwyi
    August 21, 2014 at 11:32 AM
  • Our team is riding #BikeMS to support the fight against Multiple Sclerosis. Get involved - http://t.co/GGObSd073P http://t.co/vZpWRXkQ3z
    August 21, 2014 at 9:09 AM
  • @dtkachev Thanks for the tweet! The server is back up now - sorry for the inconvenience. Have a good day!
    August 21, 2014 at 9:03 AM
  • RT @m_evans10: @joewalnes A SQL query goes into a bar, walks up to two tables and asks, "Can I join you?"
    August 20, 2014 at 3:55 PM
  • Have you read @wdpitt's newest book? - Web Essentials using #JavaScript & #HTML5. Free PDF download via @InfoQ: http://t.co/lesuPJ770I
    August 20, 2014 at 2:31 PM
Keyhole Software
8900 State Line Road, Suite 455
Leawood, KS 66206
ph: 877-521-7769
© 2014 Keyhole Software, LLC. All rights reserved.