In this case you don’t need the switch-case at all. Instead, you can tell the enum to do all the work:
| 03 |     publicvoiddoSomething() { | 
| 08 |     publicvoiddoSomething() { | 
| 13 |     publicvoiddoSomething() { | 
| 18 |   publicabstractvoiddoSomething(); | 
The switch-case then shrinks to:
| 1 | getState().doSomething(); | 
But what if the constants are defined by some third-party code? Let’s adapt the example above to match this scenario:
| 1 | publicstaticfinalintINACTIVE = 0; | 
| 2 | publicstaticfinalintACTIVE = 1; | 
| 3 | publicstaticfinalintUNKNOWN = 2; | 
Which would result in a switch-case very similar to the one above and again, you don’t need it. All you need to do is:
| 1 | Status.values()[getState()].doSomething(); | 
Regarding this case there is a small stumbling block, which you have to pay attention to. Enum.values() returns an Array containing the elements in the order they are defined, so make sure that order accords to the one of the constants. Furthermore ensure that you do not run into an ArrayOutOfBoundsException. Hint: Time to add a test.
There is yet another case that may occur. Let’s pretend you encounter some constants that aren’t as nicely ordered as the ones above:
| 1 | publicstaticfinalintINACTIVE = 4; | 
| 2 | publicstaticfinalintACTIVE = 7; | 
| 3 | publicstaticfinalintUNKNOWN = 12; | 
To cover this case, you need to alter the enum to look something like:
| 08 |   publicstaticStatus getStatusFor(intdesired) { | 
| 09 |     for(Status status : values()) { | 
| 10 |       if(desired == status.state) { | 
Even though this introduces an if (uh oh, didn’t obey rule #4), it still looks much more appealing to me than a switch-case or if-else-cascade would. Hint: Time to add another test.
How do you feel about this technique? Got good or bad experiences using it?
 
No comments:
Post a Comment