How to group cases in a switch statment? [closed]



I currently have 31 cases in my Java switch statement. Originally, there were 30 and I have now added one more.

This is giving me this sonar issue: Reduce the number of non-empty switch cases from 31 to at most 30.

How can I reduce / group the number of statements and keep the original logic?

Answer

Sonar is a tool. Not a judge, jury, or executioner. It is taking a wild stab in the dark and informing you that this code may be bad code style. It is no guarantee that it is. Sonar rules aren’t, themselves, style guidelines. The style guidelines are far too complex for software to apply. No, the sonar rule is merely a heuristic. An oversimplification. Thus, whether this warning from sonar actually means you should refactor this code depends on two factors:

  1. Once you fully understand the underlying principle that led to this sonar rule, do you even agree with the principle? If not, tell sonar to shut up (probably by globally disabling this rule for the entire codebase), add your 31st case, and move on.

  2. If you do agree with the principle, check the actual code you have. Sonar is thinking the principle, if applied to this switch you got, implies you should refactor it. Is it correct? It may not be. If you think it doesn’t, then add your 31st case, and move on.

  3. If you’re still here, then this code was always bad style; the act of adding the 31st case didn’t magically turn it into bad style, it always was. By adding the 31st, you’ve merely made it possible for sonar to tell you about it, is all. So now, make a decision, which principle is more important to you: “Do not fix what aint broke” or “refactor bad code style”? If it’s “Do not fix what aint broke”, add your 31st case, add an annotation to tell sonar to shut up, and move on.

If you’ve gotten through the entire gauntlet, refactor this code. Simply because you’re now aware that it is now and has been for a while bad style.

There is no one slam dunk answer (this is a general trend here: Coding is hard. If simple rules a computer could apply can make code better, we’d all be on Cancun sipping mohitos, letting the computers do all the programming).

A general principle that can be useful is to have a Map<X, Handler> where X is the same type as the expression X in: switch (X) { your 31 cases here }. Now you can dynamically set up your map, and for example stuff the 31 handlers into 31 separate source files, and perhaps use SPI; now you can just make a new java source file with a class implementing an interface, add a @Service annotation, and, boom, it is now part of your erstwhile switch/case construct. No need to spend time maintaining a list of all ‘handlers’, the SPI system automates it. But that’s quite a big bazooka, perhaps all you have is a mosquito. Without details, I can only give you the (generally more complex) tools that apply to all situations.



Source: stackoverflow