Always Use Braces On If Then

Problem

In C, C++ and Java, if you add another statement to the then clause of an if-then:

  if (condition)
statement1();

and forget to add the braces:

  if (condition)
statement1();
statement2();

then your code won't work right. Only statement1 is part of the if statement. Statement2 will always be executed, no matter what the value of condition is.

Therefore

Always code an if-then with braces, even when the then part contains only a single statement:

  if (condition) {
statement1();
  }
Then, when you add another statement to the then clause, you won't cause a bug.

but,

Recall also that having several lines of code managed by an "if" can be a CodeSmell that ExtractMethod is needed. In other words, refactor:

  if (expr) {
statement1;
statement2;
  }
into this:
  if (expr)
statements();

So many of us consider AlwaysUseBracesOnIfThen to be an AntiPattern


These braces are also convenient for the maintenance programmer, who will be able to delete, insert or move statements without the need to insert braces. So the code is easier (less work = cheaper) to maintain. Of course this is not restricted to if-then, but is equally valid for all control structures and leads to AlwaysUseBraces?. See BracesAreGood, BracesAroundBlocks.

Also, for people looking for "Why doesn't it work any more? Let's diff() the old version and the new version ...", when the old version already had braces, diff() picks up fewer lines of changes ... I think that's a good thing.

If the maintenance programmer happens to *delete* all but one statement inside braces, do you want him to go to the extra work of deleting the braces as well? Of course not.

However

Programmers with enough discipline to always notice the braces (and put them in when needed) don't need this idiom.

Auto-indent editors make it obvious whether your new statement is part of the else clause, making it unlikely you'll have the bug this idiom tries to prevent.

Unless one is used to always having them, it may add syntactic noise to every if-then, making it harder to read. On the other hand, once one is used to them, it is harder to read code without them. Different brace styles may help.

On the other hand, having some control statements with braces and some without is noise too. (If there's a constant background hum, that's less distracting than a tone that comes and goes.)


Alternative language designs to avoid this problem include PerlLanguage which force the use of braces, unless you use the post-fix notation:

<expression> if <condition>;
<expression> unless <condition>;
As opposed to the more traditional

if( <condition> ) { <statement>* }
if( !(<condition>) ) { <statement>* }
PythonLanguage forces IndentationEqualsGrouping and does away with braces altogether. In fact, this is probably the most (in)famous feature of Python.


In PerlLanguage, a similar issue is that of putting semi-colons on the last statement in a block.

You're allowed to do this:

if (condition) {
foo;
bar;
baz
}
But it's a bad idea, because you might want to add a line and you'd forget to put the semi-colon in where you need it:

if (condition) {
foo;
bar;
baz
quux
}
So always put the semi-colon on the last statement in a block.

Similarly, always put a comma on the last pair in a block-formatted hash assignment:

my %hash = (
foo => "bar",
baz => "quux",
);
-- KirrilyRobert

DelphiLanguage has this same problem, I'd recommend the same as above. -- AaronRobson


macros

(moved to TrivialDoWhileLoop)

AlwaysUseBracesOnIfThen when you use someone else's macros. That guards against people use fail to use the TrivialDoWhileLoop in their macros


one-liners

I only leave the braces off if: the if and the then will fit on the same line.

here is an example (from PHP) of when I think that I am justified in leaving off the braces:

 echo "<OPTION value=\"".$val."\";
  if($val==$row[$key])echo "selected";
 echo ">".$val."</OPTION>";
-- KyleJerviss

A refactoring of this PHP code which I find to be more readable:

 foreach($arraything as $key => $val)
 {
$selected == "";
if ($val == $row[$key])
{
  $selected == "selected";
}

echo "<OPTION value=\"$val\" $selected> $val </OPTION>" }
-- JonathanArkell

How about:

 foreach ($arraything as $key => $val) {
$selected = ($val == $row[$key]) ? 'selected' :  '\';
echo "<OPTION value='$val' $selected> $val </OPTION>";
 }

It avoids the if statement altogether and is very readable.

I think that code blocks should have a visible beginning and a visible end. Otherwise even code that is indented looks a little bit like an Escher to me.

Also, having something like:

 if (<expression>) statement;

reminds me a little to much of my old FORTRAN and BASIC days.

-- JohnGriffin?

IMSNHO, this is as bad or worse than leaving off braces - personally, I've become so accustomed to the body of the if-then being on the next line that I tend to have trouble reading one-line if statements. It is also more cumbersome to rewrite when you discover you need another statement in the then clause, because you need to move the line down in addition to add the new stuff. -- Pete Hardie

That is true, but that never happens in the example shown above. You are always comparing two values and spewing " selected" in one case, and nothing in the other. That'll change when the W3C decided to break all existing Web sites.

It strikes me that this page is essentially caused by the fact that you've all got text editors that make it too difficult to press return a couple of times, and put some more braces in. Or am I missing something? -- RogerLipscombe

Yes, you are referring to 'all' when you address those people that don't want to put the braces in. As I do not belong to this group, 'all' is incorrect naming for it ;-) Besides, it looks to me like this page was instigated to fight that incorrect meaning, instead of defending it. -- AndreSlabber

Among the many ways to lay out a conditional are these:

 if (expression) statement;
 else statement;

if (expression) { statement; } else { statement; }

if (expression) { statement; } else { statement; }

For sufficiently simple expressions and statements, I find the one on the top easier to look at. As complexity increases, the ones on the bottom read easier for me. -- AndyJewell

I always use a condensed version of the middle one, except as the example above.

 if(expression){
 statement;
 }else{
 statement;
 }
If that gets confusing, I usually step back, take a deep breath and figure out what's the RightThing to do. -- KyleJerviss


It's easy to put the braces in. However, doing that is bad because it wastes vertical white space, thus reducing the amount of code that will fit on screen and taxing short-term memory. It adds clutter generally, which distracts from what the code is really about. It is thus less readable.

The YouArentGonnaNeedIt principle applies. Don't make the code less readable until you have to. Although it is easy to add braces today, it will still be just as easy tomorrow, when/if the second line is needed.

I once spent a day adding debug statements to if statements to see what was running. This involved adding lots of braces since they weren't there already. At the end of the day I removed the debug statements and the brackets because I didn't change that code. A week later I found I was adding braces to some of the same ifs for the same reason. I reflected on all the problems of dangling elses, deleted statements and added statements and I decided a consistent AlwaysUseBracesOnIfThen avoided problems.

Recall also that having several lines of code managed by an "if" can be a CodeSmell that a new function is needed. In other words, refactor:

  if (expr) {
statement1;
statement2;
  }
into this:
  if (expr)
statements();
Alternatively, consider this:
  if (!expr)
return;
  statement1;
  statement2;
You seem to be saying NeverUseBracesOnIfThen?. Interesting.

These little refactorings tend to reduce the amount of indented code, so that it is actually quite rare to need more than 1 statement in the "if". (I don't mean you should never have 2 statements, just that in well-written code it is rare.)

I think these bureaucratic coding conventions, that add extra characters and extra lines where they are not needed, are one of the reasons why C++ is commonly so much more verbose than Smalltalk, and so much less pleasant to use. To write concise, elegant code you need to jettison the junk.

Spoken like a true SmalltalkBigot?... I mean LiberalPinkoCommieSmalltalker.

I would be hesitant to be forced to structure my code in order to eliminate braces. That seems to be a much more bureaucratic coding convention than trying to express the natural flow of the code. Perhaps the designers of C/C++ should have chosen to make whitespace significant in the control flow of the language, but they didn't; we got braces instead. (cf. WhitespaceIsGood, PythonWhiteSpaceDiscussion.) When scanning code, I tend to find it easiest to skip to the end of a logical group of statements by finding the closing brace and I find it painful and error prone to insert an else or else if in multiply indented control sequences without the closing braces.

The idea is that the code should (often) be restructured anyway, for other reasons, not that it should be restructured to eliminate braces.


And it makes a lot of sense. "A logical group of statements" is something that wants to be called "a method"; when you look at the braces issue in the light of how code should be refactored, it becomes obvious. Thanks for the insight. -- LaurentBossavit


If you use a decent editor (EmacsEditor), it will be obvious from the indentation whether you should have braces or not.If you don't need them, why use them? K&R don't. (I assume we're talking about C/C++/Java etc. here.)

One advantage in leaving out unnecessary braces is that because it reduces the number of lines in a function, it can sometimes make the difference between the function being entirely visible on a single screen and spilling over onto a second screen.

-- DonaldFisk


Reading through this page, I have the impression of a consensus that "Well, some less competent programmers who either can't write good code or can't read code might need the braces, but I don't need them because I'm so good." To me, this sort of argument is fine except for human nature: we're all careful and smart, but it certainly makes it easier to understand someone else's less-than-perfect code (or even my own perfect code three months later) with the braces, even if the braces do use a little more real estate on the page, and even if they do take a few hundred milliseconds to type.

An alternate interpretation may be that use of braces or not on if statements is truly interchangeable. In well written code, the braces simply do not affect the readability of the code. In poorly written code (i.e., code with very long methods with many levels of indentation), however, braces can provide some improvement. In these cases, a much stronger refactoring is required, though the insertion of braces may well be a required first step in the refactoring. In general, if one avoids creating monsters in the first place, the choice of using or not using braces becomes a personal preference and it is really not worth the effort to enforce one personal preference over another for any development team.


This may belong to a different wiki category, but it's related. What are your opinions on these:

Example1:

  private void myMethod(string parm) {
if (condition) {
... chunk of code ...
}
  }

Example2:
  private void myMethod(string parm) {
if (!condition) return;
... chunk of code ...
  }

Example2 tests the inverse and aborts, saves 2 lines of code (the braces) and saves 1 indentation level off a huge chunk of code (reducing horiz scrolling). But is it less maintainable?

A similar style question appears in loops:

Example1:

  for (int i=0; i<max; i++) {
if (condition) {
... code chunk ...
}
  }

Example2:
  for (int i=0; i<max; i++) {
if (!condition) continue;
... code chunk ...
  }

What do you guys prefer?


ItDepends. E.g. if the condition is really a check of the parameters of applicability, then checking and existing is ok (IMHO). OTOH if the condition is inherently dependent on the CodeChunk?, then surrounding it with braces is better. In short: Ask yourself: If you used ExtractMethod, would you extract the body with or without the condition?


I like the strange (though not exceptional) case to be indented.

For functions, that means induction base cases are like Example 2:

  unsigned fact(unsigned n) {
      if (!n) return 1;
      return n * fact(n);
  }
But most conditions are just like Example 1.

For loops, I would skip diagonals in a matrix like Example 2:

  for $j (0..9) {
      for $i (0..9) {
          next if $i == $j;
          # Code Chunk
      }
  }
But a find function written that way would feel strange:
  foreach (Object o in mycollection) {
      if (!o.equals(x)) continue;
      // Code Chunk
  }

-- ScottMcMurray


Indentation should demonstrate the flow of control. Putting the substatement on the same line as the flow of control construct leaves my eye looking for the end of the block. With proper brace style (*evil grin*), your first example would look like this:

  unsigned fact(unsigned n)
  {
    if (!n)
      return 1;

return n * fact(n - 1); }

Keep the braces to a minimum to preserve vertical space, but line up those that are used.


I declare this PersonalChoiceElevatedToMoralImperative. Personally I like braces-all-the-time better, but I won't claim it a universal truth. What helps or trips-up one person may not do the same to another. -top

I find myself in the rare circumstance of agreeing wholeheartedly with top. As has been noted repeatedly above, the entire issue of "needing" extraneous braces or commas or any other of the so-called "defensive" coding idiom is rendered moot by the application of good design and good coding. If one Knows What One Is Doing then one need not apply these kinds of safeties. This stuff flies in the face of conciseness, speed, ease of maintenance, etc., etc., etc.

And has been pointed out a zillion times all over this board, if one does not know what one is doing then one should not be touching the code in the first place, silly. -- MartySchrader


I just had a thing where the code formatter in NetBeans changed this

    if (something) // comment about something
        doSomething(); 

to this
    if (something) // comment about something        doSomething(); 

oops!

I'll still probably not use braces some of the time, but comments are always getting their own lines from now on.


See: WhereDoTheBracesGo, CodingStyle

CategoryDefensiveProgramming


EditText of this page (last edited August 19, 2013) or FindPage with title or text search