26

Is else while without intervening braces considered "safe" maintenance wise?

Writing if-else code without braces like below...

if (blah)
    foo();
else
    bar();

...carries a risk because the lack of braces make it very easy to change the meaning of the code inadvertently.

However, is below also risky?

if (blah)
{
    ...
}
else while (!bloop())
{
    bar();
}

Or is else while without intervening braces considered "safe"?

11
  • 20
    to me else while looks icky. I'd use else { while (condition) { ... } }. Commented Dec 20, 2012 at 9:53
  • 7
    I think it is too subjective for a proper answer ... I mzself wouldn't do it as I won't expect a loop there, and thinks I don't expect make readability hard.
    – johannes
    Commented Dec 20, 2012 at 9:53
  • 7
    I would extract method for while-stuff
    – gnat
    Commented Dec 20, 2012 at 11:08
  • 12
    Honestly, it gives me the creeps. if is only evaluated once, but while denotes a loop, so connecting both gives me a unsubstantiated feeling that the if is part of the loop... somehow...
    – user281377
    Commented Dec 20, 2012 at 11:20
  • 4
    And what if in the else clause you want to do the while and do something more? Just use braces, please. Commented Dec 20, 2012 at 14:29

11 Answers 11

57

That reminds me this code:

if ( ... ) try {
..
} catch (Exception e) {
..
} else {
...
}

Every time you are combining two types of blocks, forgetting braces and not increasing indentation, you are creating code very difficult to understand and maintain.

3
  • 19
    Good example. What a horrible way to write it.
    – Leo
    Commented Dec 20, 2012 at 15:32
  • 5
    Wow, this answer is ridiculously convincing!
    – user541686
    Commented Dec 20, 2012 at 18:02
  • You can easily set up modern IDEs to automatically format code on saving - including inserting braces and correcting the indentation. So this is only half an argument. Properly indented this would pose no problem for readability, whether there are braces or not. Commented Jan 10, 2013 at 15:12
55

Perhaps it is because I learnt my trade (way back when) using the Jackson Entity Structure Diagram method, but I subscribe to the view that the only correct unbraced term after an if or an else is a subsequent if (ie allowing an else if ladder)

Anything else (no pun intended) leaves potential for misunderstanding and/or maintenance issues. That is the central aspect of the OPs idea being "unsafe".

I'd also be very cagey about including the while() on the same line as the else - whether braced or not. It doesn't read right to me... the lack of any extra indentation masks that it is the else clause. And lack of clarity makes for misunderstandings (see above).

So in the example I would strongly advise/recommend (and insist, in my team) on:

if ( blah )
{
    ...
}
else
{
    while ( !bloop() )
    {
        bar();
    }
}

Of course, I would also expect to see suitable comments too.

-- Edit --

Recently Apple suffered from an SSL vulnerability, caused by a poor maintenance fix - that added a second line to an un-braced single line. So let's put to bed the idea that unbraced single lines are OK?

5
  • 2
    I agree on if being the only correct term to follow an else. If there was an else while I would probably not even notice there was a loop in a quick skimming of the code, especially if the condition I was looking for was satisfied by the if. Commented Dec 20, 2012 at 13:28
  • 3
    It's funny. Everyone says that it's easier to read if everything is in braces. I find the opposite to be true. If it's only one statement, keeping it out of braces makes it easier to read. Less clutter. It may only be because I have always done it that way.
    – Jeff Davis
    Commented Dec 20, 2012 at 15:11
  • 2
    @JeffDavis that's a good catch. "Easier to read" is a typical invitation to useless holy war. I for one prefer braces, but not because of irrelevant "easiertoread" garbage (to me for example it's exactly the opposite) but because it's harder to break in further code maintenance. By the way OP spelled it better in their question: is else while without intervening braces considered "safe"?
    – gnat
    Commented Dec 20, 2012 at 18:30
  • @JeffDavis - I know this thread is two years old, but Apple recently discovered why not using braces is not a good idea andrewbanks.com/…
    – Andrew
    Commented Oct 25, 2014 at 7:56
  • @Andrew By the way, Apple's Swift language now explicitly forbids one-line flow control. That bug could be one of the reasons to do so.
    – Sulthan
    Commented Nov 4, 2016 at 18:28
6

I have always been taught to keep everything in braces, indented and commented. I believe it's much easier to read and spot errors. Personally i feel modularity is key so i would always write the code like this :

    if(blah)
    {
     ....
    }
    else
    {
       while(!bloop()
       {
        bar;
       }
    }
6

I would extract method and make it

if ( blah )
{
    ...
}
else
{
   newMethod();
}

See "extract method" approach explained at Refactoring Catalog site:

You have a code fragment that can be grouped together.

Turn the fragment into a method whose name explains the purpose of the method.

void printOwing() {
    printBanner();

    //print details
    System.out.println ("name:    " + _name);
    System.out.println ("amount    " + getOutstanding());
}

                                                                                                         http://www.refactoring.com/catalog/arrow.gif

void printOwing() {
    printBanner();
    printDetails(getOutstanding());
}

void printDetails (double outstanding) {
    System.out.println ("name:    " + _name);
    System.out.println ("amount    " + outstanding);
}
2
  • Depends... if for example, the while loop used function level data, you're now having to more that data to module (or class, if using C++) level. And if only a small snippet of code, you're into trivial methods. But sometimes, depending on circumstances, I'd agree.
    – Andrew
    Commented Dec 20, 2012 at 14:20
  • 1
    +1 Smart C++ compilers can inline a function. In .Net environment small functions are better due to JIT.
    – Job
    Commented Dec 25, 2012 at 16:47
4

I would consider it as a bad habit of coding. Sometimes it works perfectly fine and you will have no problem in compiling and running the code. At other times it may cause serious bugs and you will end up spending hours in fixing that bug.

It is always recommended to modularize your code. If you have to put a while loop in else part put it in a block so that others, when working on your code can easily understand the logic.

if ( blah )
{
    ...
}
else
{
    while ( !bloop() )
    {
        bar();
    }
}

It's a good practice to put code in blocks. It makes it simpler and easier to understand and debug as well.

4

It might be fine if it stays simple like that although personally I don't like it and my preference is to use braces even for the simplest if/else code blocks. It's just tidier for me.

However, where this gets messy is when you have nested if/else loops some with braces some without. A While loop in the middle of all that spaghetti! I've worked with code that bad and it's a nightmare to debug and to understand. This follows on from the first point it's fine when it stays simple and you're happy with it, but then other programmers come along and add things to it, probably an if else within the while loop. If it's written clean in the first place then there's less chance of this happening.

The point is to make stuff clear so that other programmers can see at a glance what's right and wrong. Write code so that the pattern looks right and doesn't jar.

The flip side of this is that maybe I could see some people claiming that in certain instances this reads well. If I've got the resource I need do this processing else while I'm waiting for something do this. Even then to me there's still no difference in nesting the while loop inside the else block.

3

Well, despite everyone argues about using braces and seem to love them, I actually prefer the opposite. I only use braces when I have to because I find it more readable and concise without.

if (...)
   foo();
else while(...)
   bar();

...I actually find this "else while(...)" remarkably readable! It even reads like plain English! But I guess people will all find it strange because it's unusual to say the least.

In the end, we all tend to make it idiot-proof with braces though ...because, well, you know.

5
  • 3
    that'll be especially readable after some innocent maintainer changes else while(...) bar(); to something like else while(...) foobar(); bar(); :)
    – gnat
    Commented Dec 20, 2012 at 14:20
  • 3
    well, I would say that is a pretty stupid and dangerous innocent maintainer. I know the principle of dumbing it down to avoid stupid errors ...but going so far is nevertheless fairly sad. But I knew I'd get such comments and downvotes. No problem.
    – dagnelies
    Commented Dec 20, 2012 at 14:26
  • 2
    "Always code as if the person who will maintain your code is a violent psychopath who knows where you live." (Alan Braggins)
    – gnat
    Commented Dec 20, 2012 at 14:44
  • 1
    Well, everything boils down to what you assume the stupidest level of someone working on your code would be. I argue that if your "maintainer" gets confuser by these four lines of code ...then you have a massive problem at hands. And if it's a violent psycho, you have two. ;)
    – dagnelies
    Commented Dec 20, 2012 at 15:07
  • 2
    if - well the link I refer in above, has expanded version of this quote: Programmer 1: 'There's a nice quote here - "Always code as if the person who will maintain your code is a violent psychopath who knows where you live"'. Programmer 2: (Looks over at maintainer) 'What do you mean "as if"?'
    – gnat
    Commented Dec 20, 2012 at 15:40
3

What is so wrong with braces that so many people is trying to avoid writing them ?

What problem does exactly else while solve ?

Braces are cheap and good, and they make code intention evident and plain as opposed to clever and witty.

Quoting Unix Philosophy:

Rule of Clarity: Clarity is better than cleverness.

Because maintenance is so important and so expensive, write programs as if the most important communication they do is not to the computer that executes them but to the human beings who will read and maintain the source code in the future (including yourself).

2

I always put braces, just because you might add another line when in hurry, indent it, forget the braces and scratch your head what's happening. I keep the opening bracket on the same line, but it doesn't matter. I both cases it's better to have them.

if(blah) {
    foo();
}
else {
    bar();
}
2
  • Positioning of braces probably triggers more argument than anything beyond (or possibly including) religion!
    – Andrew
    Commented Dec 20, 2012 at 14:10
  • Agreed. Will edit my answer to emphasize on their existence, not position. Commented Dec 20, 2012 at 14:52
1

There's nothing wrong with

if (blah)
    foo();
else
    bar();

just like there's nothing wrong with

if (blah) foo(); else bar();

in the right circumstances (your circumstances may vary, but that particular style is best used when you have a lot of repetitive code - then the view of each line is more important than the stylistic indentation)

But if you choose one way, keep to it - consistency is king. So your second example is very bad, as the if expression had brackets for its statement, the while statement should be inside the brackets for the else clause, not outside it.


besides, I have seen this code before:

if (x) foo()
{
  bar();
}

and it was written by the coding standard nazi himself (who insisted on brackets for everything).

1

Modern IDEs can easily be configured to reformat (including removing or adding unnecessary braces) and/or reindent the code on saving a file. Thus your example would automatically look like for instance

if (blah) {
  blub();
} else
  while (!bloop()) {
    bar();
  }

The indentation always makes the nesting easily visible, even without unneccesary braces. So, if you manage to enforce such IDE settings, I see no risk.

Personally, I find code that omits the braces and linebreaks much more readable since it avoids clutter:

if (blah) blub();
else while (!bloop()) bar();

But of course, many developers are very happy to argue about such things forever and a day.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.