1

I have around 100 non-empty cases inside a switch case. Each case calls different functions. Sonar is showing issue to reduce number of non-empty switch cases to atmost 30. Is there any alternative to implement such switch cases or there is no problem in having any number of switch cases.

    for(int i=0;i<arrayList.size();i++){
       switch(arrayList.get(i)){
          case "A":
             a();
            break;

          case "B":
             b(10,20);
            break;

             ...
             ...

          case "ABZ":
             abz("string1","string2");
           break;
       }
    }
  • How about rethinking your design? Large number of `case` in a `switch-case` is difficult to maintain. Please provide sample code that provides a hint on how your `switch-case` is structured? – Prashant Apr 16 '20 at 05:25
  • How can i do so. Can you please explain? – Srikanth Reddy Kallem Apr 16 '20 at 05:27
  • Strategy design pattern might help. – Prashant Apr 16 '20 at 05:32
  • Updated the sample code. Please look into it. At a time arrayList have 30 random numbers between 1 to 100. based on that number i want to execute a particular function – Srikanth Reddy Kallem Apr 16 '20 at 05:39
  • How about using `HashMap` to store Integer and corresponding `Function` and call the function based on the random number? – Prashant Apr 16 '20 at 05:49
  • storing in HashMap and calling is more difficult to maintain than switch i guess. what do you say? – Srikanth Reddy Kallem Apr 16 '20 at 05:52
  • Does this answer your question? [Turning Sonar off for certain code](https://stackoverflow.com/q/10971968/5221149) --- You accept that you are writing code not conforming to Sonars general rules, but decide that you need to bypass that rule, in this particular case, because you truly have to act 100 different ways depending on an `int` value. – Andreas Apr 16 '20 at 05:58
  • No Andreas... thats not a perfect solution to turn off sonar and get rid of it – Srikanth Reddy Kallem Apr 16 '20 at 06:02
  • I think, that `HashMap` (incapsulated in a class to avoid key duplicates and to check, that all ways a set) or Strategy, probably with Visitor (you use a special interface instead of strings in your arrayList) are, IMHO, better way as 100 cases. – mickle_ak Dec 31 '21 at 12:17

1 Answers1

0

I don't know how to implement this idea in Java, but maybe this might help you out. I had a switch case similar to yours with over a 100 non-empty cases in Javascript. What I ended up doing was create a dictionary (key-value) to replace the switch case, where the value was a closure (a function that returns a function) like so:

const myDictionary = {
"A": ()=>functionA(),
"B": ()=>functionB(10, 20)
"C": ()=>functionC()
}

A dictionary look-up is faster than using a switch case, so that's an easy approach without making any big change in the design pattern

for(int i=0;i<arrayList.size();i++){
 myDictionary[arrayList.get(i)]()
}
Manuel Duarte
  • 644
  • 4
  • 18