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

后端 未结 11 1636
-上瘾入骨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.

提交回复
热议问题