Java - avoid switch statements for static functions

java, oop, polymorphism, switch-statement

Solution

I would have an `enum` like so:

enum Kind {
    GREEN {
        @Override
        public void doSomething() {
            GreenKind.doSomething();
        }
    },
    WHITE {
        @Override
        public void doSomething() {
            WhiteKind.doSomething();
        }
    };

    public abstract void doSomething();
}

And pass around an enum constant, for example this method:

public static void invoke(Kind kind) {
    kind.doSomething();
}

and call it like:

invoke(Kind.GREEN);

This way looks cleaner, and moreover it's safer, as you can have only a fixed set of inputs.

Problem

Check out this code - ``` switch(kind) { case "green" : GreenKind.doSomething(); // Static function break; case "white" : WhiteKind.doSomething(); // Static function break; case "blue" : BlueKind.doSomething(); // Static function break; case "yellow" : YellowKind.doSomething(); // Static function break; } ``` There is a way to avoid the switch statement? as it smells real bad. Maybe to somethnig like this? - ``` kinds.get(kind).doSomething(); ``` The problem with my solution is that the functions are static, and i can't implement an interface with static functions. If you didn't understood why i wrote interface its because i wanted to use polymorphism in my solution above.

Original source