Tutorial :Formatting of if Statements



Question:

This isn't a holy war, this isn't a question of "which is better".

What are the pros of using the following format for single statement if blocks.

if (x) print "x is true";    if(x)       print "x is true";  

As opposed to

if (x) { print "x is true"; }  if(x) {      print "x is true";      }  

If you format your single statement ifs without brackets or know a programmer that does, what led you/them to adopt this style in the first place? I'm specifically interested in what benefits this has brought you.

Update: As the most popular answer ignores the actual question (even if it presents the most sane advice), here's a roundup of the bracket-less pros.

  1. Compactness
  2. More readable to some
  3. Brackets invoke scope, which has a theoretical overhead in some cases


Solution:1

For me, braces make it easier to see the flow of the program. It also makes it easier to add a statement to the body of the if statement. When there aren't braces, you have to add braces to add another statement.

I guess the pros of not using braces would be that it looks cleaner and you don't waste a line with a closing brace.


Solution:2

Lines spacing and indentation can do alot for readability.

As far as readability I prefer the following:

// Do this if you only have one line of code  // executing within the if statement  if (x)      print "x is true";    // Do this when you have multiple lines of code  // getting executed within the if statement      if (x)  {      print "x is true";  }  


Solution:3

I wish the IDE would enforce this behaviour. As you correctly pointed out there is no "right" behaviour. Consistency is more important ... it could be either style.


Solution:4

I feel like outvoted so far, but I'll vouch for one of:

if (expr) {     funcA();  }  else {     funcB();  }  

Or, shorthand in limited cases for readability:

if (expr) funcA();  else funcB();  

To me, the shorthand format is nice when you want it to read like English grammar. If the code doesn't look readable enough, I'll break out the lines:

if (expr)     funcA();  else     funcB();  

With careful consideration I don't put nested conditionals within the if/else blocks to avoid coder/compiler ambiguity. If it's any more complex than this, I use the braces on both if and else blocks.


Solution:5

Any formatting of this type is fine. People will argue with you black and blue over this because it is something easy to understand. People like to talk about things they understand instead of dealing with bigger problems such as good design and solving hard problems with new algorithms. I tend to prefer no brackets for simple one-liners. However, I am also happy to read it with brackets. If there is a particular style guide for a given project I prefer to follow that. I believe in consistency over some subjective ideal of correctness.

My personal choice for no brackets for one-liners is due to typing less characters, shorter code and succinctness.


Solution:6

Of the options provided, I'd go with

if (x) {    print "x is true";      }  

simply by virtue of the braces being habit to type.

Realistically, though, as a mostly-Perl programmer, I'm more likely to use

print "x is true" if x;  

(Which always trips me up when I'm working in a language which doesn't support postfix conditionals.)


Solution:7

I prefer single line statements with out brackets, I know that there is the danger that I can forget to add them when I insert a new line of code, but I cannot remember the last time this happened. My editor (vim) prevents me to write things like this:

  if (x)      x = x + 1;      printf("%d\n", x);  

because it will indent it differently. The only thing I had problems with, are bad written macros:

  #define FREE(ptr) {free(ptr); ptr = NULL;}    if (x)      FREE(x);  else      ...  

This doesn't work of course, but I think it is better to fix the macro, to avoid those possible bugs or problems instead of changing the formating style.

So there are possible problems with that way of formating, but they are imho not fatal. It ends up to be a matter of taste.


Solution:8

I haven't seen anyone mention the most useful reason to place the bracket on the same line as the if -- bracket matching in emacs. When you place the cursor on the ending bracket, emacs shows the line with the matching start bracket. Placing the start bracket on its own line, negates the feature.


Solution:9

I prefer the following...i think it looks cleaner.

if(x)  {      code;  }  else  {       other code;  }  


Solution:10

I guess I'm more of an outlier than I thought; I haven't noticed this one yet.

I'm a fan of

if (x)  { foo(); }  

It feels compact & readable (I hate sprawling braces), but it makes the scope of the condition explicit.

It's also more breakpoint-friendly than single-line if's. It also feels more at home in my braces-on-newline world:

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

Edit: it appears I misread the original question, so this answer off-topic. I'm still curious about any response, though.


Solution:11

One liners are just that... one liners and should remain like this :

if (param == null || parameterDoesNotValidateForMethod) throw new InvalidArgumentExeption("Parameter null or invalid");  

I like this style for argument checking for example,it is compact and usually reads easily. I used to put braces with indented code all the time but found that in many trivial cases it just wasted spaces on the monitor. Dropping the braces for some cases allowed me to get into the meat of methods faster and made the overall presentation easier on the eyes. If however it gets more involved then I treat it like everything else and I go all out with braces like so :

if (something)  {      for(blablabla)      {      }  }else if  {   //one liner or bunch of other code all get the braces  }else  {    //... well you get the point  }  

This being said... I despise braces on the same line like so :

if(someCondition) { doSimpleStuff; }  

of worst

if(somethingElse){    //then do something  }  

It is more compact but I find it harder to keep track of the braces.

Overall it's more a question of personal taste so long as one does not adopt some really strange way to indent and brace...

    if(someStuff)          {    //do something          }  


Solution:12

I believe that this is the most important reason, and I’m astounded to see that it hasn’t been given as an answer yet (although it has been mentioned in a comment, a footnote in an answer, and an aside in an answer).

You should always use brackets, because

if (x)     DoSomething();  

breaks if DoSomething is subsequently redefined to be a multi-statement macro:

#define DoSomething()          statement1 ;  statement2 ;

Of course, we all know that the right thing to do is to define the macro like this:

#define DoSomething()    do {  statement1 ;  statement2 ;  } while (0)
which makes the macro behave more like a statement.

That said, I admit that I don’t follow my own advice; I usually don’t use braces when I have (what appears to be) a single statement.  (Hangs head in shame.)


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »