What is the benefit of terminating if … else if constructs with an else clause?

前端 未结 12 1033
不思量自难忘°
不思量自难忘° 2020-11-27 13:37

Our organization has a required coding rule (without any explanation) that:

if … else if constructs should be terminated with an el

12条回答
  •  温柔的废话
    2020-11-27 13:57

    Only a brief explanation, since I did this all about 5 years ago.

    There is (with most languages) no syntactic requirement to include "null" else statement (and unnecessary {..}), and in "simple little programs" there is no need. But real programmers don't write "simple little programs", and, just as importantly, they don't write programs that will be used once and then discarded.

    When one write an if/else:

    if(something)
      doSomething;
    else
      doSomethingElse;
    

    it all seems simple and one hardly sees even the point of adding {..}.

    But some day, a few months from now, some other programmer (you would never make such a mistake!) will need to "enhance" the program and will add a statement.

    if(something)
      doSomething;
    else
      doSomethingIForgot;
      doSomethingElse;
    

    Suddenly doSomethingElse kinda forgets that it's supposed to be in the else leg.

    So you're a good little programmer and you always use {..}. But you write:

    if(something) {
      if(anotherThing) {
        doSomething;
      }
    }
    

    All's well and good until that new kid makes a midnight modification:

    if(something) {
      if(!notMyThing) {
      if(anotherThing) {
        doSomething;
      }
      else {
        dontDoAnything;  // Because it's not my thing.
      }}
    }
    

    Yes, it's improperly formatted, but so is half the code in the project, and the "auto formatter" gets bollixed up by all the #ifdef statements. And, of course, the real code is far more complicated than this toy example.

    Unfortunately (or not), I've been out of this sort of thing for a few years now, so I don't have a fresh "real" example in mind -- the above is (obviously) contrived and a bit hokey.

提交回复
热议问题