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

烈酒焚心 提交于 2019-12-06 18:01:31

问题


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 should write else part in every if condition" . Suppose we have no condition for write in else part then what should we do ? I assume a healthy discussion will going on here....


回答1:


That's a horrible idea. You end up with code of the form:

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

How anyone could think that's more readable or maintainable that not having an else at all is beyond me. It sounds like one of those rules made up by people who have too much free time on their hands. Get them fired as quickly as you can, or at least move away calmly and quietly :-)




回答2:


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.




回答3:


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.




回答4:


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))



回答5:


Looking at this purely from a semantic point of view - I cannot think of a single case where there is not an implicit else for every if.

if the car is not stopped before I reach the wall I will crash, else I will not crash.

Semantics aside:

The answer to that question depends on the environment, and what the result of a mistake is.

Business code? Do what your coding standards say.
IMHO you will find that spelling it out, although initially it seems like too much work, will become invaluable 10 years from now when you revisit that code. But, it certainly would not be the end of the world if you missed an important 'anti-condition'.

However: Security, Safety or Life Critical code? That's a different story.

In this case you want to do two things.
First:Rather than testing for a fault, you want to prove there is not a fault. This requires a pessimistic view on entry to any module. You assume everything is wrong until you prove it is correct.
Second: in life critical: You NEVER want to hurt a patient.:

bool everyThingIsSafe = true;
if(darnThereIsAProblem())
{
   reportToUserEndOfWorld();
}
return everyThingIsSafe;

Oops. I forgot to set everyThingIsSafe false.
The routine that called this snippit is now lied to. Had I initialized evertThingIsSafe to false - I'm always safe, but now I need the else clause to indicate that there wasn't an error.
And yes, I could have changed this to a positive test - but then I need the else to handle the fault.
And yes, I could have assigned everyThingIsSafe() the immediate return of the check. And then tested the flag to report a problem. An implicit else, why not be explicit?
Strictly speaking, the implicit else this represents is reasonable.
To an FDA/safety auditor, maybe not.
If it's explicit, can point to the test, its else, and that I handled both conditions clearly.

I've been coding for medical devices for 25 years. In this case, you want the else, you want the default in the case, and they are never empty. You want to know exactly what is going to happen, or as near as you can. Because overlooking a condition could kill someone.

Look up Therac-25. 8 severely injured. 3 dead.




回答6:


Sometimes there is no else part....and including an empty one just makes the code less readable imho.




回答7:


No, you don't have to ..

Also, I don't think that it is a good idea for readability, since you will have lots of empty else blocks. which will not be pretty to see.




回答8:


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.




回答9:


No, but I personally choose to always include encapsulating braces to avoid

if (someCondition)
    bar();
    notbar();  //won't be run conditionally, though it looks like it might

foo();

I'd write

 if (someCondition){
        bar();
        notbar();  //will be run
 }
 foo();



回答10:


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



回答11:


No, It's not required to write the else part for the if statement.

In fact most of the developers prefer and recommend to avoid the else block.

that is

Instead of writing

if (number >= 18) {
    let allow_user = true;
} else {
    let allow_user = false;
}

Most of the developers prefer:

let allow_user = false;
if (number >= 18) {
    let allow_user = true;
}


来源:https://stackoverflow.com/questions/3393921/is-it-necessary-to-write-else-part-in-every-if-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!