Note that there are some explanatory texts on larger screens.

plurals
  1. POReusing code in switch statement (Java)
    text
    copied!<p>I would like to use a <code>switch</code> statement, but I am not able to construct it without either duplicating code or using an accompanying <code>if</code> statement. Is there a way around this?</p> <p>I have 5 cases, and for all but one of them I would like to perform a certain action. So with a <code>switch</code> statement, I can just do:</p> <pre><code>switch(x) { case A: foo(); break; case B: case C: case D: case E: bar(); break; } </code></pre> <p>Easy. But the difficulty comes in that I also need to perform another distinct action for each one, so I can't use the fall-through feature of the cases. So I'm reduced to either</p> <pre><code>switch(x) { case A: foo(); baz(0); break; case B: bar(); baz(1); break; case C: bar(); baz(2); break; case D: bar(); baz(3); break; case E: bar(); baz(4); break; } </code></pre> <p>which smells to me because of having to repeat <code>bar()</code> every time, or</p> <pre><code>switch(x) { case A: baz(0); break; case B: baz(1); break; case C: baz(2); break; case D: baz(3); break; case E: baz(4); break; } if (x != A) { bar(); } </code></pre> <p>which doesn't duplicate any code, but it bothers me that there I need to use both <code>switch</code> and <code>if</code>.</p> <p>I guess one other alternative would be to use a map, like</p> <pre><code>Map&lt;X, Integer&gt; m = new HashMap&lt;X, Integer&gt;(); m.put(A, 0); m.put(B, 1); m.put(C, 2); m.put(D, 3); m.put(E, 4); if (m.get(x) == 0) { foo(); } else { bar(); } baz(m.get(x)); </code></pre> <p>but now I've introduced a whole data structure just to clean this up. (And when you count the initialization of the map, it's not even that much cleaner.)</p> <p>Any tips?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload