Suppose you have an enum
type like this:
public enum Type
{
A, B, C, D, E, F
}
Then you want to do something depending on some of the values, so you create a switch sentence:
switch (type)
{
case Type.A: // Do something
break;
case Type.B: // Do something
break;
case Type.C: // Do something
break;
}
This compiles and works fine, but then Sonarqube 5.2 (with the default rules for C#) examines the code and complains about the switch
not having a default case (it qualifies it as a major issue). So you change the code to this:
switch (type)
{
case Type.A: // Do something
break;
case Type.B: // Do something
break;
case Type.C: // Do something
break;
default: // Do nothing
break;
}
But then it's SharpDevelop who complains, graying the default case and telling you that the code should not be there as it does nothing.
So you end up changing the code to an if
sentence:
if (type == Type.A) // Do something
else if (type == Type.B) // Do something
else if (type == Type.C) // Do something
With this code, neither SonarQube nor SharpDevelop complain at all. Well, SharpDevelop kindly suggests that the if
can be converted into a switch
.
So, which way is better? Should I add the default case to the switch
and ignore SharpDevelop? Should I ignore the issue in SonarQube? Or should I just go for the if
sentence? Is there any other way to do it more properly?
Well, you should always have a default case in my opinion. I throw an exception in the default case because it indicates that there is something that I forgot to code (usually an added enum value, for example) and makes it clearly evident where the bug is.
What you do, of course, depends on what the default case implies in your application. Is there truly a state where "do nothing" is an okay path through the code? That's usually indicative of a defect or brittle code that should lead to refactoring. The same goes for if
blocks without else
which you proposed as a work-around. In fact, I'm surprised sonarqube doesn't complain about that, too.