Java - avoid switch statements for static functions

Check 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; } 

Is there a way to avoid the switch statement? as it smells bad.

Maybe something like that? -

 kinds.get(kind).doSomething(); 

The problem with my solution is that the functions are static and I cannot implement an interface with static functions. If you did not understand why I wrote the interface because I wanted to use polymorphism in my solution above.

+6
source share
2 answers

I would have enum like this:

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

And pass the enum constant, for example, this method:

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

and name it like this:

 invoke(Kind.GREEN); 

This method looks cleaner and is also safer since you can only have a fixed set of inputs.

+15
source

You can use an enumeration. Example for listing with one record:

 public enum Kind { GREEN("green") { @Override public void doSomething() { /* do something */ } }; private final String asString; public abstract void doSomething(); Kind(final String asString) { this.asString = asString; } @Override public String toString() { return asString; } } 

In code, you should do Kind.valueOf(kind.toUppercase()).doSomething(); .

It will also allow you to get rid of {Green, Red} Kind with a little work: just put all the logic in an enumeration.

+3
source

All Articles