Just trying to figure out how to use many multiple cases for a Java switch statement. Here's an example of what I'm trying to do:
switch (variable)
{
case 5..100:
doSomething();
break;
}
versus having to do:
switch (variable)
{
case 5:
case 6:
etc.
case 100:
doSomething();
break;
}
Any ideas if this possible, or what a good alternative is?
for alternative you can use as below:
or the following code also works
Maybe not as elegant as some previous answers, but if you want to achieve switch cases with few large ranges, just combine ranges to a single case beforehand:
The second option is completely fine. I'm not sure why a responder said it was not possible. This is fine, and I do this all the time:
// Noncompliant Code Example
//Compliant Solution
From the last java-12 release multiple constants in the same case label is available in preview language feature
It looks like:
See more JEP 325: Switch Expressions (Preview)
One Object Oriented option to replace excessively large
switch
andif/else
constructs is to use aChain of Responsibility Pattern
to model the decision making.Chain of Responsibility Pattern
Here is an example implementation that is also Type Safe using Generics.
This is just a quick straw man that I whipped up in a few minutes, a more sophisticated implementation might allow for some kind of
Command Pattern
to be injected into theCase
implementations instances to make it more of a call back IoC style.Once nice thing about this approach is that Switch/Case statements are all about side affects, this encapsulates the side effects in Classes so they can be managed, and re-used better, it ends up being more like Pattern Matching in a Functional language and that isn't a bad thing.
I will post any updates or enhancements to this Gist on Github.