Reputation: 1
Recently, I've found a piece of code which looks like this.
switch(type)
{
case TYPE1:
doSomething1(type, arg1);
break;
case TYPE2:
doSomething2(type, arg1, arg2);
break;
}
Why don't just pass explicitly those enums (TYPE1, TYPE2) instead of passing the type variable? Like in the following example.
switch(type)
{
case TYPE1:
doSomething1(TYPE1, arg1);
break;
case TYPE2:
doSomething2(TYPE2, arg1, arg2);
break;
}
I understand that such repetition is OK when the variable is reused in:
switch(type) { case TYPE1: case TYPE2: case TYPE3: someFunction(type, arg1, arg2); break; }
But in the first example it seems to be useless.
What do you think about that? Is there any advantage of such convention?
Upvotes: 0
Views: 123
Reputation: 1
switch(type)
{
case TYPE1:
doSomething1(type, arg1);
break;
case TYPE2:
doSomething2(type, arg1, arg2);
break;
}
Upvotes: -3
Reputation: 38315
The first snippet is superior to the second one when it comes to maintainability. Imagine you want to change the branch conditions, e.g. invert TYPE1
and TYPE2
: with the first snippet, you have two edits, with the second, there are four.
With regard to your interpretation that passing the flag might be "useless": whether the functions invoked from different branches do need the enum flag or not can't be judged from the example you show. If they don't, it's safe to remove the enum from the function signature. But having such a fallthrough
switch (type) {
case TYPE1:
case TYPE2:
doSomething(type /*, ... */);
}
suggests that there will be another branching in doSomething
depending on type
, which probably is unnecessary code duplication and/or a violation of separation of concerns.
Upvotes: 5