Reputation: 292
I had the following scenario where an easy fix which jumped to my mind which would have prevented a simple bug.
Following code was presented:
var dialogAnswer = new SomeActionSheet("Option 1 as string", "Option 2 as string", "Option 3 as string");
switch(dialogAnswer)
{
case "Option 1 as string":
DoSomething();
break;
case "Option 2 as string":
DoSomething();
break;
}
Later on, one answer option string was changed in the dialog, but got forgotten in the switch/case, which resulted in nothing happening, since there was also a "default" case missing.
It came to my mind, that this would have been easily be prevented had I used a variable instead of a string. And since switch/case only allows constants, I would have to use something like:
private const string answerOption1 = "Option 1 as string";
But if I look in larger projects I never/rarely saw a switch case where constant string variables where used.
So my question is, is this bad practice or just not common and should I use normal strings instead of const variables in switch/cases? Or would it be even better to use an enum in cases similar to mine?
Upvotes: 3
Views: 1002
Reputation: 2107
Yes it is generally bad practice to use the same string (or any inline value) multiple times in the same project as doing so deviates from the fundamental DRY principle.
This principle is widely considered a good philosophy to follow until there are reasons why it cannot be employed efficiently in a specific scenario. These could include performance edge-cases or intentional decoupling of dependencies for share nothing scenarios. You have not highlighted either of these requirements.
Having a single constant will mitigate errors either when building, refactoring, or deleting code.
Yes you could use an Enum instead of a string. This is also a constant. It also serializes to a number, can be packed as bit flags, and is faster to evaluate than a string of indeterminate length. It also avoids encoding issues.
Upvotes: 3