4
if(var == something) {
    A();
    B();
} else if(var == something_else) {
    A();
    B();
    C();
} else {
    assert(false);
}

How can i avoid duplicate code of calling A() and B() in both if cases. Should i use switch case like,

switch(var) {
case something:
case something_else:
    A();
    B();
    break;
}
if (var == something_else)
   C():

What is the better solution? Is there any performance penalty in switch vs if else?

Jagdish
  • 1,848
  • 3
  • 22
  • 33

4 Answers4

6
if (var == something || var == something_else) {
    A();
    B();
}

if (var == something_else) {
    C();
}

If you also need the else, you can do this:

if (var == something || var == something_else) {
    A();
    B();

    if (var == something_else) {
        C();
    }
} else {
    assert(false);
}

In regards to your question,

Is there any performance penalty in switch vs if else?

Please read the answers to this question:

Is 'switch' faster than 'if'?

In short, normally there wouldn't be any noticeable difference. So you should write your code with the readability in mind. Between if/else and switch, just choose whatever is more natural.

Community
  • 1
  • 1
Dmytro Shevchenko
  • 33,431
  • 6
  • 51
  • 67
2

As calling order doesn't matter, try this:

switch(var) {    
    case something_else:
        C();
    case something:
        A();
        B();
    break;
    default:
        assert(false);
    break;
}
mazhar islam
  • 5,561
  • 3
  • 20
  • 41
2

You can use a nested if statement for this, like so:

If (var == something || var == something_ese) {
    A();
    B();
    If (var == something_else) { C(); }
}
Else
{
    Assert(false);
}
Sufian Latif
  • 13,086
  • 3
  • 33
  • 70
Magisch
  • 7,312
  • 9
  • 36
  • 52
1

I would suggest separating the assert and the work:

assert(var == something || var == something_else);

A();
B();
if(var == something_else) {
    C();
}

Not only this avoids duplication of A and B calls, but also makes it more readable as you specify the pre-requisites right at the beginning.

Petr
  • 9,812
  • 1
  • 28
  • 52