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

后端 未结 21 1198
迷失自我
迷失自我 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 07:12

    I use the following short hand just for fun! Don't try anyof these if code clearity concerns you more than the number of chars typed.

    For cases where doX() always returns true.

    i==1 && doOne() || i==2 && doTwo() || i==3 && doThree()
    

    Ofcourse I try to ensure most void functions return 1 simply to ensure that these short hands are possible.

    You can also provide assignments.

    i==1 && (ret=1) || i==2 && (ret=2) || i==3 && (ret=3)
    

    Like instad of writting

    if(a==2 && b==3 && c==4){
        doSomething();
    else{
        doOtherThings();
    }
    

    Write

    a==2 && b==3 && c==4 && doSomething() || doOtherThings();
    

    And in cases, where not sure what the function will return, add an ||1 :-)

    a==2 && b==3 && c==4 && (doSomething()||1) || doOtherThings();
    

    I still find it faster to type than using all those if-else and it sure scares all new noobs out. Imagine a full page of statement like this with 5 levels of indenting.

    "if" is rare in some of my codes and I have given it the name "if-less programming" :-)

提交回复
热议问题