views:

1147

answers:

12

Duplicate:

Why is it considered a bad practice to omit curly braces?


Hey folks,

Just curious on your thoughts about the below:

if (someCondition) {
      callSomething();
}

vs.

if (someCondition)
      callSomething();

I only ask this because when I started using refactoring tools, the if without curly braces is what they refactored to. Where I used to work we did this all the time, then I was reading a book, Crockford's awesome JavaScript: The Good Parts, and he was saying removing the curly braces caused more coding errors and really wasn't worth saving the two characters. So I started coding again minus the curly bracket refactor.

Just wondering what you folks all think about this.

+3  A: 

The former helps when you have to add a second line (or more) to the if condition later on. So keep `em.

dirkgently
Unfortunately, it also encourages cramming 2 (or more) statements within each block, rather than splitting up your code...
Shog9
Are you suggesting that there should be only one statement following an if statement? That's outrageous.
dirkgently
@dirkgently: no. I'm suggesting that it's a bad idea to just cram more code into a routine without thinking it through carefully. If the result of a conditional test will be a laundry-list of actions, then wrap 'em in a block; if it will be a single action, then don't. If more complicated logic is needed, then split it out...
Shog9
Real world code doesn't pan out that way. Some bug fixes are nasty. Sometimes you don't want the overhead of calling a function.
dirkgently
And what? If the person modifying the routine knows that function call overhead is going to break something, they're almost certainly well past the point of caring about niggling style issues.
Shog9
It's not about style. It's about scope. You want a couple of statements in a scope, you put them there.
dirkgently
A: 

If condition and function name are short enough I usually put them on a single line.

if (someCondition) callSomething();

However, I usually try to avoid both and stick to a more functional style that employs the conditional operator.

int variable = someCondition ? callSomething() : callSomethingElse();

or

int variable = callSomething(someCondition);

with the conditional operator (? :) embedded in callSomething.

Waylon Flinn
The problem is that "functional style" and actually functional are very different. The ? : operator is expected to be part of an expression, if callSomething and or callSomethingElse have any side effects then its poor form to call them in ? : . Clearly from the question callSomething has side effects.
AnthonyWJones
In all languages that support the conditional operator that I am aware of, only one of the expressions on each side of the ':' symbol will be evaluated, so side effects are not an issue.
anon
I don't see any part of the question that implies side effects exist in callSomething. However, if they do my suggestion would be a refactor. Burying side effects at the bottom of deep call trees makes code much less maintainable.
Waylon Flinn
@Neil: You've miss understood the notion of a side effect. If callSomething modifies anything other than its own local variables and its return value that _is_ a side effect. That is a bad thing to happen when all you appear to have done is evaluate an expression. IOW a functional style looks functional but actually isn't is simply not a good idea.
AnthonyWJones
@Waylon: If the callSomething() function doesn't actually modify something then what would be the point in calling it. If it returns something without changing anything else in the program state then its a valid function to place in a ? : expression.
AnthonyWJones
anon
@Anthony In this context I would typically call a function without side effects to calculate a value (or create another object) based on object state. I would (ideally) reserve side effects for top level functions like event handlers.
Waylon Flinn
I just followed the link to the duplicate question. I found it interesting how similar the top answers there are to mine. The primary difference appears to be my advocating a more functional approach.
Waylon Flinn
+11  A: 
if (someCondition)
   if ( someOtherCondition )
      callSomething();
else
   callSomethingElse();

Quick! From a glance at the code, which if does the else associate with?

anon
nesting ifs smells bad
Waylon Flinn
In this case one would use the curlies to make things clear but that doesn't necessarily rule out the simpler example in the question.
AnthonyWJones
I find it easier to have a blanket rule that produces readable code in all cases.
anon
I've seen code exactly like this in a production codebase. It was the source of a bug -- the inner if block was added at a later point and accidently stole the else block for itself.While I agree that the simpler example shouldn't necessarily be ruled out, I do think that leaving off the curly braces *can* lead to bugs in the real world if you're not careful.
Naaff
@Naaff: modifying existing code without bothering to understand it *can* - and usually does - lead to bugs in the real world.
Shog9
@Neil: I prefer principled programming rather than rule based progamming, the case displayed in the question is actually quite common and the curlies are just noise. Yes I know I'm in the minority here.
AnthonyWJones
+4  A: 

I always keep the curly braces. Removing them is just asking for trouble, and for no benefit (if you object to typing two more characters, you probably shouldn't be a programmer).

However, I don't have a problem with keeping everything on one line, if there's room. In this case, I'd write it

if (someCondition) { callSomething(); }

Takes up only a single line, but still has the braces so I don't accidentally introduce bugs.

jalf
The reason people object is for readability, not writability I would think.
Joe Philllips
Do you find this unreadable though? I think if anything it aids readability (I don't have to look up and down or match braces on different lines to find the extents of the scope, and I'm able to fit a few more lines of code on the screen.
jalf
A: 

If I have a series of if-conditions in a row I will use the single-line version without curly braces.

if (x) return true;
if (y) return true;
if (z) return true;

If I have a single if-condition I will use curly braces whether it's on one line or not.

if (x) { return true; }
Joe Philllips
anon
A: 

Personally, I'll eliminate the brackets under the following conditions:

  • The condition and the action can readably fit on the same line
  • The contained action isn't another block (loop, if, etc.)

Otherwise the brackets are always there.

Adam Robinson
A: 

For the most part, it's purely a stylistic choice. Some even use this style to protect themselves from accidentally forgetting about the lack of curly braces:

if (foo) doBar();

However, if abused and used incorrectly, it's possible to make code much more confusing than it has to be:

if (foo)
   if (bar)
      doBaz();
   else if (thing)
      doOtherThing();
else (something)
   doThatThing();

See, that last else block is incorrectly lined up, but without the braces, it's hard to tell.

But in general, as long as you use one-line if statements wisely, I don't see anything wrong with them.

htw
+3  A: 

I say use the braces. It makes your code consistent looking and, as already mentioned, the condition may get bigger than one line and you'll need to add them in anyway.

mfdoran
A: 

I would recommend always using braces in the case you give, so that you never have to think about whether to add them or not, and you never have to edit them in and out as the code changes.

quamrana
A: 

In the very simple case of:

if (condition)
    oneFunctionHereOnly();

or

if (condition)
   oneFunctionHereOnly();
else
   someotherSingleFunctionHereOnly();

I don't bother with the curlies. For one I find code that places an opening { in same column as its corresponding } much more readable but with that restriction the above code becomes 8 lines instead of 4.

AnthonyWJones
A: 

I always put the braces as I believe it adds to maintainability. If I have ...

if( somePredicate )
  doThatThang();

I am always afraid a maintenance programmer will come along and change it to ...

if( somePredicate )
  doThatThang();
  andThatThang();

without adding the brackets. Also, to me, the brackets add a sense of symmetry to the code.

JP Alioto
+3  A: 

Using the braces is technically "unnecessary" and just fills the code with meaningless empty space. (Empty space in code is very important, but only where it is meaningful)

I use a simple rule. If any statement contains a child scope (if, while, for, etc) then I omit the curly braces only if the statement and its child occupy one line each. (Bearing in mind that I also use a maximum of one statement per line)

That is,

if (condition)
  return;            -- "if" and child scope are 1 line each, no braces

and:

if (condition1 ||
    condition2)      -- "if" occupies more than 1 line, so use braces
{
  return;
}

if (condition)
{
  value = 1;         -- child scope contains more than 1 line, so use braces
  return;
}

if (condition)
{
  // We will return now  -- A comment is still a line, so use braces
  return;
}

This applies regardless of what the lines are (comments, code, etc). That makes the rule very simple to apply, which eliminates any chance of making mistakes.

Note that it is generally recommended that we place the braces at the same indent level, as that symmetry (and the indent) provide a visual confirmation that the code is correctly formed. i.e. You can see that the "shape" of the code is correct, without having to actually read it, so any errors stick out like a sore thumb. By placing the open brace on the end of the if statement, there is no visual symmetry and you have to actually read the code to be sure that the scope is correctly formed.

I've not had a scoping error in over 20 years of programming (C, Java, C++, C#) using these rules.

Jason Williams