I have seen many instances of the code looking dirty with very long Switch statement or If elses. Even lot of googling didn’t give me proper answer on what should be the right design to avoid such long code. So here I have attempted to solve such type of codes in practice and create Enum based design to replace Switch statement.

Suppose we have situation where we need to perform some operation using switch cases like below.

//problem area
public void perform(char input) {
    switch (input) {
        case 'X':
            performX();break;
        case 'Y':
            performY();break;
        case 'Z':
            performZ();break;
        default:
            System.out.print("do nothing...");
    }
}

and we have our class which contains required methods

public class Actor {
    public void performX() {
        System.out.print("performing...X");
    }
    public void performY() {
        System.out.print("performing...Y");
    }
    public void perfromZ() {
        System.out.print("performing...Z");
    }
}

Now change the hierarchy of class Actor with the help of an interface IActor

interface IActor {
    public void perform();
}
public abstract class Actor implements IActor {
}
class ActorX extends Actor {
    public void perform() {
        System.out.print("performing...X");
    }
}
class ActorY extends Actor {
    public void perform() {
        System.out.print("performing...Y");
    }
}
class ActorZ extends Actor {
    public void perform() {
        System.out.print("performing...Z");
    }
}

Now lets create an Enum and call it Action

public enum Action {
    X(new ActorX()), Y(new ActorY()), Z(new ActorZ());
    private IActor actor;
    private Actions(IActor actor) {
        this.actor = actor;
    }
    public void perform() {
        actor.perform();
    }
}

Finally, simply replace the the code in our problem area with below code.

//Solution Area
public void perform(char input) {
    Action.valueOf(String.valueOf(input)).perform();
}

 

Posted in

2 responses to “Design Pattern to avoid Switch Case or Multiple If elses”

  1. Sudheer Yarashi Avatar

    Hello Vishal,

    Design Pattern for Switch Case is a Nice Idea actually.

    Liked It.

    Like

    1. Vishal Nigam Avatar

      Thank you Sudheer.

      Like

Leave a comment