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

后端 未结 21 1197
迷失自我
迷失自我 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:24

    I regard these if-elseif-... constructs as "keyword noise". While it may be clear what it does, it is lacking in conciseness; I regard conciseness as an important part of readability. Most languages provide something like a switch statement. Building a map is a way to get something similar in languages that do not have such, but it certainly feels like a workaround, and there is a bit of overhead (a switch statement translates to some simple compare operations and conditional jumps, but a map first is built in memory, then queried and only then the compare and jump takes place).

    In Common Lisp, there are two switch constructs built in, cond and case. cond allows arbitrary conditionals, while case only tests for equality, but is more concise.

    (cond ((= i 1)
           (do-one))
          ((= i 2)
           (do-two))
          ((= i 3)
           (do-three))
          (t
           (do-none)))

    (case i (1 (do-one)) (2 (do-two)) (3 (do-three)) (otherwise (do-none)))

    Of course, you could make your own case-like macro for your needs.

    In Perl, you can use the for statement, optionally with an arbitrary label (here: SWITCH):

    SWITCH: for ($i) {
        /1/ && do { do_one; last SWITCH; };
        /2/ && do { do_two; last SWITCH; };
        /3/ && do { do_three; last SWITCH; };
        do_none; };
    

提交回复
热议问题