Note that there are some explanatory texts on larger screens.

plurals
  1. POWhen should one try to eliminate a switch statement?
    text
    copied!<p>I've come across a switch statement in the codebase I'm working on and I'm trying to figure out how to replace it with something better since <a href="http://c2.com/cgi/wiki?SwitchStatementsSmell" rel="nofollow noreferrer">switch statements are considered a code smell</a>. However, having read through <a href="https://stackoverflow.com/questions/126409/ways-to-eliminate-switch-in-code">several</a> posts on stackoverflow about <a href="https://stackoverflow.com/questions/374239/why-doesnt-python-have-a-switch-statement#374290">replacing</a> <a href="https://stackoverflow.com/questions/561401/refactor-my-c-code-switch-statement">switch</a> <a href="https://stackoverflow.com/questions/338206/switch-statement-with-strings-in-java">statements</a> I can't seem to think of an effective way to replace this particular switch statement.</p> <p>Its left me wondering if this particular switch statement is ok and if there are particular circumstances where switch statements are considered appropriate.</p> <p>In my case the code (slightly obfuscated naturally) that I'm struggling with is like this:</p> <pre><code>private MyType DoSomething(IDataRecord reader) { var p = new MyType { Id = (int)reader[idIndex], Name = (string)reader[nameIndex] } switch ((string) reader[discountTypeIndex]) { case "A": p.DiscountType = DiscountType.Discountable; break; case "B": p.DiscountType = DiscountType.Loss; break; case "O": p.DiscountType = DiscountType.Other; break; } return p; } </code></pre> <p>Can anyone suggest a way to eliminate this switch? Or is this an appropriate use of a switch? And if it is, are there other appropriate uses for switch statements? I'd really like to know where they are appropriate so I don't waste too much time trying to eliminate every switch statement I come across just because they are considered a smell in some circumstances.</p> <p><strong>Update:</strong> At the suggestion of <a href="https://stackoverflow.com/questions/1071856/when-should-one-try-to-eliminate-a-switch-statement/1071879#1071879">Michael</a> I did a bit of searching for duplication of this logic and discovered that someone had created logic in another class that effectively made the whole switch statement redundant. So in the context of this particular bit of code the switch statement was unnecessary. However, my question is more about the appropriateness of switch statements in code and whether we should always try to replace them whenever they are found so in this case I'm inclined to accept the answer that this switch statement is appropriate.</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