What is the best way to replace or substitute if..else if..else trees in programs?

后端 未结 21 975
迷失自我
迷失自我 2020-11-28 06:23

This question is motivated by something I\'ve lately started to see a bit too often, the if..else if..else structure. While it\'s simple and has its uses, somet

相关标签:
21条回答
  • 2020-11-28 06:59

    In python, I would write your code as:

    actions = {
               1: doOne,
               2: doTwo,
               3: doThree,
              }
    actions[i]()
    
    0 讨论(0)
  • 2020-11-28 07:01

    I would go so far as to say that no program should ever use else. If you do you are asking for trouble. You should never assume if it's not an X it must be a Y. Your tests should test for each individually and fail following such tests.

    0 讨论(0)
  • 2020-11-28 07:02

    Use a switch/case it's cleaner :p

    0 讨论(0)
  • 2020-11-28 07:03

    Use a Ternary Operator!

    Ternary Operator(53Characters):

    i===1?doOne():i===2?doTwo():i===3?doThree():doNone();
    

    If(108Characters):

    if (i === 1) {
    doOne();
    } else if (i === 2) {
    doTwo();
    } else if (i === 3) {
    doThree();
    } else {
    doNone();
    }
    

    Switch((EVEN LONGER THAN IF!?!?)114Characters):

    switch (i) {
    case 1: doOne(); break;
    case 2: doTwo(); break;
    case 3: doThree(); break;
    default: doNone(); break;
    }
    

    this is all you need! it is only one line and it is pretty neat, way shorter than switch and if!

    0 讨论(0)
  • 2020-11-28 07:06

    A switch statement:

    switch(i)
    {
      case 1:
        doOne();
        break;
    
      case 2:
        doTwo();
        break;
    
      case 3:
        doThree();
        break;
    
      default:
        doNone();
        break;
    }
    
    0 讨论(0)
  • 2020-11-28 07:06
    switch (i) {
      case 1:  doOne(); break;
      case 2:  doTwo(); break;
      case 3:  doThree(); break;
      default: doNone(); break;
    }
    

    Having typed this, I must say that there is not that much wrong with your if statement. Like Einstein said: "Make it as simple as possible, but no simpler".

    0 讨论(0)
提交回复
热议问题