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

12

19

My question might get closed, but I'm curious about whether it's always required to add an "else" part to every "if" statement in coding. A senior programmer told me, "You should always have an 'else' part in every 'if' statement." However, what should we do if there's no reason to include an "else" part? I think this could lead to an interesting discussion.

Emetic answered 3/8, 2010 at 5:59 Comment(5)
I try not to "should" on my peers. It tends to get messy. Use an else only if it makes sense.Funderburk
"if" you always listen to your co-workers, you will pick up their bad habits. There's no need to to say " 'else' you get to learn for yourself".Vermicelli
I think your senior programmer actually said, "you should think about the else part in every if condition". I've seen too much fall through code because of missing else blocks.Decortication
Seems like here is a better answer: #35053871Clyte
Kubernetes calls this "Space Shuttle Style" and it's used to help ensure correctness - worth reading: github.com/kubernetes/kubernetes/blob/…Gatepost
P
17

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

Pirog answered 3/8, 2010 at 6:3 Comment(6)
"One option is to code the else clause—with a null statement if necessary—to show that the else case has been considered. Coding null elses just to show that that case has been considered might be overkill, but at the very least, take the else case into account. When you have an if test without an else, unless the reason is obvious, use comments to explain why the else clause isn’t necessary." - Code Complete I feel conflicted, what do you think ?Contrasty
I think, like so much stuff quoted from that book, it needs to be in context: the preceding sentence is: "If you think you need a plain if statement, consider whether you don't actually need an if-then-else statement." Every bit of code I write is the result of informed consideration like that: nn this case, rejected since a decent programmer will know that a missing else clause means no action should be taken. I don't read a function and wonder about the seven lines that were never placed at the end of it, that's exactly the attitude you should take to the missing else :-)Pirog
The problem with this great book is that it makes very obvious/beginnerish statements from time to time. E.g in the preceding page, it says you should avoid 'if-then-else' statements where the 'if' block has no statements in its body and instead negate the test condition (I am paraphrasing).Contrasty
Not that I am complaining though. I will in any day choose a book which makes obvious statements over one which contains enigmatic obscurities because the author drew the line between obvious/non-obvious (which may never be possible in the first place, since everyone has different knowledge/experience) in the wrong place.Contrasty
Here is my downvote for you. I've seen too much silent bugs caused by a fallthrough code caused by an if condition without an else clause. "If condition is not met, nothing will happen" is just wrong in many cases. You can always add an exception or a log entry to the else clause.Refractory
@Jeyekomon, I find that thinking rather bizarre. For a start, there are plenty of scenarios where you want to do something for one case, and nothing at all for the opposite case. You even admit as such with your quote "in many cases". Adding a log is going to be unhelpful in these cases (and absolutely not fix any real problem with the code flow that may exist), adding an exception will be catastrophic since you now have to handle that totally unnecessary exception in the using code. Bottom line, consider whether an else block is needed but don't put in empty ones for no value.Pirog
C
8

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.

Capel answered 3/8, 2010 at 6:4 Comment(0)
C
5

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))
Communard answered 3/8, 2010 at 6:23 Comment(1)
+1 for being the only answer to mention the if-else expression.Filamentary
E
4

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.

Experience answered 3/8, 2010 at 6:3 Comment(0)
E
1

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.

Endodontics answered 24/1, 2014 at 17:40 Comment(0)
P
1

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
Panchromatic answered 10/2, 2015 at 8:59 Comment(0)
A
1

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;
}
Alpenglow answered 22/8, 2019 at 11:8 Comment(0)
A
0

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.

Ammonium answered 3/8, 2010 at 6:0 Comment(0)
V
0

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();
Vermicelli answered 3/8, 2010 at 6:4 Comment(1)
My rule is that inline (on one line) ifs need no braces, but if the contents of the statement are in another line, then braces are necessary.Zabaglione
E
0

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

Emrick answered 3/8, 2010 at 6:4 Comment(0)
Z
0

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.

Zabaglione answered 3/8, 2010 at 6:5 Comment(0)
S
0
def in_num(num):
    if num % 3 == 0:
        print("fizz")
    if num % 5 == 0:
        print("buzz")
    if (num % 3 !=0) and (num % 5 !=0):
        print(num)

see in this code else statement is not necessary.

Storekeeper answered 7/1, 2022 at 7:26 Comment(1)
Its a fizz buzz question where else is not necessary.Storekeeper

© 2022 - 2024 — McMap. All rights reserved.