Refactoring if/else logic

You should use Strategies, possibly implemented within an enum, e.g.:

enum UserType {
  ADMIN() {
    public void doStuff() {
      // do stuff the Admin way
    }
  },
  STUDENT {
    public void doStuff() {
      // do stuff the Student way
    }
  };

  public abstract void doStuff();
}

As the code structure within each outermost if branch in your code looks pretty much the same, in the next step of refactoring you might want to factor out that duplication using template methods. Alternatively, you might turn Location (and possibly Age) into a strategy as well.

Update: in Java4, you can implement a typesafe enum by hand, and use plain old subclassing to implement the different strategies.

Leave a Comment