Maciej Kulesza
Maciej Kulesza

Reputation: 1

Code style: Reuse of a control expression or control variable in the branch of a switch/if statement

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

Answers (2)

Ghada Alosaimi
Ghada Alosaimi

Reputation: 1

switch(type)
{
    case TYPE1:
        doSomething1(type, arg1);
        break;
    case TYPE2:
        doSomething2(type, arg1, arg2);
        break;
}

Upvotes: -3

lubgr
lubgr

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

Related Questions