Is it necessary to write else part in every if condition?

后端 未结 11 1654
-上瘾入骨i
-上瘾入骨i 2021-02-19 05:16

The question I asked might be closed, But i just want to know that is it necessary to write else part of every if condition. One of my senior programmer said me that \"you shoul

相关标签:
11条回答
  • 2021-02-19 05:39

    No, you certainly don't have to - at least in most languages. (You didn't specify; it's quite possible that there's a language which does enforce this.) Here's an example where I certainly wouldn't:

    public void DoSomething(string text)
    {
        if (text == null)
        {
            throw new ArgumentNullException("text");
        }
        // Do stuff
    }
    

    Now you could put the main work of the method into an "else" clause here - but it would increase nesting unnecessarily. Add a few more conditions and the whole thing becomes an unreadable mess.

    This pattern of "early out" is reasonably common, in my experience - and goes for return values as well as exceptions. I know there are some who favour a single return point from a method, but in the languages I work with (Java, C#) that can often lead to significantly less readable code and deeper nesting.

    Now, there's one situation where there's more scope for debate, and that's where both branches are terminal, but neither of them is effectively a shortcut:

    public int DoSomething()
    {
        // Do some work
        if (conditionBasedOnPreviousWork)
        {
            log.Info("Condition met; returning discount");
            return discount;
        }
        else
        {
            log.Info("Condition not met; returning original price");
            return originalPrice;
        }
    }
    

    (Note that I've deliberately given both branches more work to do than just returning - otherwise a conditional statement would be appropriate.)

    Would this be more readable without the "else"? That's really a matter of personal choice, and I'm not going to claim I'm always consistent. Having both branches equally indented gives them equal weight somehow - and perhaps encourages the possibility of refactoring later by reversing the condition... whereas if we had just dropped through to the "return original price", the refactoring of putting that into an if block and moving the discount case out of an if block would be less obviously correct at first glance.

    0 讨论(0)
  • 2021-02-19 05:42

    Danger! Danger, Will Robinson!

    http://en.wikipedia.org/wiki/Cargo_cult_programming

    Is the inclusion of empty else { } blocks going to somehow improve the quality, readability, or robustness of your code? I think not.

    0 讨论(0)
  • 2021-02-19 05:43

    This is purely a matter of style and clarity. It's easy to imagine if statements, particularly simple ones, for which an else would be quite superfluous. But when you have a more complex conditional, perhaps handling a number of various cases, it can often be clarifying to explicitly declare that otherwise, nothing ought to be done. In these cases, I'd leave a // do nothing comment in the otherwise empty else to it clear that the space is intentionally left blank.

    0 讨论(0)
  • 2021-02-19 05:45

    In imperative languages like Java and C, if - else is a statement and does not return a value. So you can happily write only the if part and go on. And I think that it is the better practice rather than adding empty elses after every if.

    However in functional languages like Haskell and Clojure, if is an expression and it must return a value. So it must be succeeded with an else. However there are still cases where you may not need an else section. Clojure, for such cases, has a when macro which wraps if - else to return nil in the else section and avoid writing it.

    (when (met? somecondition)
      (dosomething))
    
    0 讨论(0)
  • 2021-02-19 05:46

    I know I am late but I did a lot of thinking over this and wanted to share my results.

    In critical code, it is imperative for every branch is accounted for. Writing an else is not necessary, but leave a mark that else is not necessary and why. This will help the reviewer. Observe:

    //negatives should be fixed
    if(a < 0) {
        a+=m;
    }
    //else value is positive
    
    0 讨论(0)
提交回复
热议问题