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.
Therefore nested switch statements should be avoided. Specifically, you should structure your code to avoid the need for nested switch statements, but if you cannot, then consider moving the inner switch to another function.
Luckily, JavaScript's object literals are a pretty good alternative for most switch statement use-cases I can think of. The idea is to define an object with a key for each case you would have in a switch statement. Then you can access its value directly using the expression you would pass to the switch statement.
A switch statement is usually more efficient than a set of nested ifs. Deciding whether to use if-then-else statements or a switch statement is based on readability and the expression that the statement is testing.
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.
You can use an enum. Example for a single entry enum:
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 would then do Kind.valueOf(kind.toUppercase()).doSomething();
.
This would also allow you to get rid of {Green,Red}Kind with a little work: just put all the logic into the enum.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With