59

Which is better/more generally accepted?

This:

if(condition)
{
  statement;
}

Or:

if(condition)
  statement;

I tend to prefer the first one, because I think it makes it easier to tell what actually belongs in the if block, it saves others from adding the braces later (or creating a bug by forgetting to), and it makes all your if statements uniform instead of some with braces and some without. The second one, however, is still syntactically correct and definitely more compact. I'm curious to see which is more generally preferred by others though.

Adam Lear
  • 31,939
  • 8
  • 101
  • 125
Zann Anderson
  • 433
  • 2
  • 8
  • 13

17 Answers17

131

The first is better because the second is error-prone. For example, let's say you are temporarily commenting out code to debug something:

if(condition) 
//      statement;
otherStatement;

Or adding code in a hurry:

if(condition) 
    statement;
    otherStatement;

This is obviously bad. On the other hand, the first one does feel too verbose at times. Therefore, I prefer to just put everything on one line if it's sufficiently short and simple:

if(condition) statement;

This cuts down on syntactic noise while making the construct look like it does what it actually does, making it less error-prone. Provided that this syntax is only used for very simple, short conditions and statements, I find it perfectly readable.

dsimcha
  • 17,224
  • 9
  • 64
  • 81
  • 35
    Good point about putting everything on one line. – Neil Aitken Nov 03 '10 at 14:50
  • 1
    But what about if statement is looooooooong ? :) – artjom Nov 03 '10 at 14:53
  • @artjomka then refactor to a method. – Steven Evers Nov 03 '10 at 14:55
  • 7
    @artjomka: If statement is long, and has to go on its own line, then I use braces for readability. The point is that you want the shortest, least syntactically noisy construct that is unambiguous to a human who is reading it quickly rather than scrutinizing it. – dsimcha Nov 03 '10 at 14:56
  • Yes. If the next day you have to think about it to figure out what you wrote yesterday, it probably isn't very clear. – Michael K Nov 03 '10 at 15:05
  • 3
    I prefer to do this, but our new coding standards (enforced by some VS template) decree a newline after all conditional statements. So now I have to add the braces (which means a one-line statement now takes up four lines). – TMN Nov 03 '10 at 15:19
  • 15
    I prefer the one with braces for the reasons already mentioned. I don't like the one-liner, because it is not immediately obvious what happens when I step over the line in the debugger. I have to take the separate step to see what condition evaluates to. – Jim A Nov 03 '10 at 16:25
  • +1. Glad to see I'm not the only one who resorts to one line if statements. – Maulrus Nov 03 '10 at 16:37
  • 10
    @TMN whitespace is free, monitors are big and your brain learns to recognise the shape which helps you parse the code. – Murph Nov 03 '10 at 20:52
  • 2
    Although I can agree with the one-liner. Don't remember where I got this quote, but it illustrates my opinion: "If I don't put curly-braces around my if-statement consequent statement, another programmer will add a second statement assuming the braces are there but invisible, and bears will eat him." – ronag Nov 03 '10 at 22:53
  • @Murph - I second the "brain learns the shape" argument - I'm pretty well used to expecting an if block to look a certain way, and that "shape" includes the braces. – Zann Anderson Nov 04 '10 at 05:24
  • @Murph: Monitors seem to be getting fatter and shorter -- I have a 19" 1600x1200 monitor at home, but my 22" monitor at work is only 1680x1050. Height is indeed an issue. – TMN Nov 04 '10 at 15:17
  • @TMN hmm, I cut my teeth on 80x25 character screens and did a lot of useful work at VGA and SVGA resolutions... in braces on multiple lines is the "right way" and it didn't get to be the right way purely on a whim. But if you don't like it so long as you conform to the coding standards of your organisations/projects who am I to argue. – Murph Nov 04 '10 at 16:36
  • 5
    @Murph: whitespace is free? I must have missed that. On my screen, it takes up really much space. Much more than 50% actually. Which in my book seems like a big waste. Personally, I like to maximize content per square centimeter in code. – Konrad Rudolph Nov 04 '10 at 16:56
  • 4
    @Konrad: I feel exactly the opposite, I prefer short lines and small groups of lines. Most of my methods contain blank lines just for the sake of separating different steps, I feel it makes it easier to read, it's the paragraph idea: the reader can just concentrate on one paragraph at a time, and when the step has been understood, move on to the next. And I rarely have paragraphs more than 4/5 lines long. – Matthieu M. Nov 06 '10 at 13:40
  • 1
    @Matthieu: I feel exactly the same (read my answer below). But closing braces introduce *two* newlines (well, every sane code I’ve ever seen puts an extra newline after the closing brace). And that’s just too much separation. – Konrad Rudolph Nov 06 '10 at 13:44
  • @Konrad: You make a compelling case in your answer, I still prefer dmischa's case for either having a single line (with the if) or using braces but I do understand now that I took your previous comment vastly out of context. – Matthieu M. Nov 06 '10 at 13:59
  • @TNM : Whitespace is not free. Smaller fonts and larger fields of view increase cognitive loading, and thus perceptual error rates. – hotpaw2 Dec 03 '11 at 06:25
  • When people who complain about wasted lines, I wonder, why do half of them use the brace style where even the `{` goes on its own new line. Baffling. I prefer a 3 line if stmt over a 4 line one. I'd also like to take the time to advocate programmnig on a portrait monitor display. You see TONS of lines. – Thomas Eding Jul 27 '12 at 17:48
  • The one-liner does not work with most debuggers (it is not possible to trigger a break when the content of the 'if' clause is about to be executed). – Peter Mortensen May 31 '14 at 18:51
  • @hotpaw2: On the contrary. Smaller fonts and larger fields of view increase the amount that the programmer can see at one time. It is well-known that programmer comprehension of code falls off dramatically the moment he has to start scrolling his terminal or flipping pages of a listing. Read "Psychology of Computer Programming", by Gerald Weinberg. – John R. Strohm May 31 '14 at 22:29
44

I always use brackets just to be safe.

It's fine when you write it, but you know somebody will come along in the future and insert another statement without putting brackets around it.

Neil Aitken
  • 261
  • 2
  • 6
  • 20
    Have people really seen this happen? I don't think I've ever seen this in 10 years of programming. Maybe I've just been too sheltered. :) – David Nov 03 '10 at 15:35
  • 9
    I'd love to say no, but sadly I have seen it. – Neil Aitken Nov 03 '10 at 15:58
  • 13
    You always use brackets so that you never forget to use brackets - its as simple as that. – Murph Nov 03 '10 at 20:49
  • 12
    +1 to @Murph. Same reason I use my turn signals when nobody's around--and in parking lots! – Dan Ray Nov 03 '10 at 23:58
  • 7
    This is good practice to help prevent errors when merging from branch-to-trunk or across branches. – JBRWilkinson Nov 04 '10 at 11:01
  • 2
    @David: I've done it myself many, many times (sometimes on my own code) – Christian Mann Nov 06 '10 at 07:39
  • 3
    Even worse is when someone comments out the statement without commenting out the corresponding if check (and yes I've seen this happen) – jeff charles Dec 03 '11 at 05:45
  • @David, yes, I have seen this happen. I used to write my if block without braces if there was only one statement in it, assuming that anyone wanting to add more statements would be smart and attentive enough to add the curly braces, until someone did exactly what Neil described. That was what made me change my habit. – Elias Zamaria Jul 27 '12 at 18:11
  • 1
    @David apparently **yes** - https://gist.github.com/kman007us/9191386 – Kevin Meredith Feb 24 '14 at 16:19
27

I prefer the version without braces where possible.

The following explanation is longish. Please bear with me. I will give a compelling reason for me to prefer this style. I will also explain why I think that the usual counter-argument doesn’t hold.

(Near-) empty lines are a waste

The reason for this is that the closing brace requires an extra line of code – and so does the opening brace, depending on style.1

Is this a big deal? Superficially, no. After all, most people also put empty lines in their code to separate logically slightly independent blocks, which vastly improves readability.

However, I detest wasting vertical space. Modern monitors actually have ample horizontal space. But vertical space is still very, very limited (unless you use a monitor turned upright, which isn’t that uncommon). This limited vertical space is a problem: it’s widely acknowledged that individual methods should be as short as possible, and that corresponding braces (or other block delimiters) should be no more than a screen height in difference so that you may see the entire block without scrolling.

This is a fundamental problem: once you can’t see the entire block on your screen any longer, it gets complicated to grasp.

As a consequence, I detest redundant empty lines. Where single empty lines are crucial to delimit independent blocks (just look at the visual appearance of this text), consecutive empty lines are a very bad style in my book (and in my experience they are usually a sign of novice programmers).

Likewise, lines which simply hold a brace, and which could be economised, should be. A single-statement block which is delimited by braces wastes one to two lines. With only 50-ish lines per screen height, this is noticeable.

Omitting braces maybe does no harm

There is just one argument against omitting braces: that someone will later add another statement to the block in question and will forget to add the braces, thus inadvertently changing the semantics of the code.

This would indeed be a big deal.

But in my experience, it isn’t. I’m a sloppy programmer; and yet, in my decade of programming experience, I can honestly say that I have not once forgotten to add the braces when adding an extra statement to a singleton block.

I even find it implausible that this should be a common mistake: blocks are a fundamental part of programming. Block level resolution and scoping is an automatic, ingrained mental process for programmers. The brain just does it (otherwise, reasoning about programming would be much harder). There is no additional mental effort required to remember putting the braces: the programmer also remembers to indent the newly added statement correctly, after all; so the programmer has already mentally processed that a block is involved.

Now, I am not saying that omitting braces doesn’t cause mistakes. What I’m saying is that we have no evidence one way or the other. We simply don’t know whether it causes harm.

So until someone can show me hard data, collected from scientific experiments, demonstrating that this is indeed an issue in practice, this theory remains a “just-so story”: a very compelling hypothesis that has never been put to the test, and that must not be used as an argument.


1 This problem is sometimes solved by putting everything – including the braces – on the same line:

if (condition)
{ do_something(); }

However, I believe it’s safe to say that most people despise this. Furthermore, it would have the same problems as the variant without braces so it’s the worst of both worlds.

Konrad Rudolph
  • 13,059
  • 4
  • 55
  • 75
  • 6
    Omitting braces harms readability and can easily cause issues when the code is modified. – Josh K Nov 03 '10 at 16:20
  • 15
    @Josh: the first claim is ridiculous, as languages such as Python show (back it up with evidence if you think otherwise). The second has been countered in my answer. Do you have evidence to back it up? Otherwise your comment is an indication that you haven’t actually read my text. Please do so before criticising it. – Konrad Rudolph Nov 03 '10 at 16:25
  • 8
    +1 for your thoughts, but I think your position is self-defeating. You say "show me hard data, collected from scientific experiments, showing that this is indeed an issue in practice" and yet fall back on anecdotal experience (your own) to defend your position. You say, "in my experience...in my decade of experience...I find it implausible..." and so forth. Can you show hard data, collected from scientific experiments, supporting your claim, "Omitting braces does no harm"? Personal experience is fine when supporting an opinion, but don't ask for more "evidence" than you're willing to give. – bedwyr Nov 03 '10 at 18:59
  • 3
    @bedwyr: there’s a qualitative difference, though. First, I make it clear that I will actually be persuaded by data, and I make it equally clear that mine is merely a hypothesis, *not* backed up by data. Secondly, I have stated an (at least to me) plausible argument for my belief that the claim is false and why it needs to be corroborated. Which leads me to thirdly: the onus here is on the opposition to prove their claim, not on me to disprove it. And in addition to the plausibility problem, I have shown one unrelated factual argument supporting my coding style. – Konrad Rudolph Nov 03 '10 at 19:52
  • 4
    @Konrad - python *does not* show otherwise because the indentation is significant and hence the braces are implicit. Good bright programmers, the type who are here, probably won't make the mistake often if at all (in a lot of years I've probably seen issue with on only a couple of occasions) but there are a lot of rather less good programmers out there who do do stupid things which is one of the reasons why coding standards are needed in the first place. (And because deadlines and stress can make the best of us less good.) – Murph Nov 03 '10 at 21:02
  • 1
    @Murph: my Python point was levelled solely at the readability argument. Omitting braces, given proper indentation, does *not* harm readability. This *is* indeed shown by Python *because* whitespace is significant. If the missing braces would harm readability so, Python’s readability would be impaired. – Konrad Rudolph Nov 03 '10 at 21:14
  • @bedwyr: I’ve changed some formulations and and added a clarification. Is that better? (Have a look at the [revisions](http://programmers.stackexchange.com/posts/16550/revisions) to see the changes clearly). – Konrad Rudolph Nov 05 '10 at 12:14
  • 1
    @Konrad: I don't have any hard data, I do have a few anecdotes where the introduction of a statement caused a bug. Funny to say, all happened while tracking a bug by people who would add a trace in the `if` block to see if it was actually executed or not. And of course I did too. You feel pretty stupid then (even though it doesn't happen that often) and therefore vow yourself never to be bitten by it, which I think lead to this extreme position that put curly braces for every single line statements. Programmers don't like their ego to be bruised :) – Matthieu M. Nov 06 '10 at 13:57
  • You write very well. – kirk.burleson Nov 11 '10 at 03:55
  • It just occurred to me: I wonder if it's more common for people to forget to add braces when adding another statement to the if-block when they use a style that puts the opening brace on the same line as the if condition. Visually it's harder to tell at a glance whether or not there is already a statement block defined when using that style, because the positioning of the statement relative to the if condition is the same. I put the opening brace on its own line, and I agree that it's hard to forget to add braces, but I wonder if it's more common to forget them if using the other style. – Dr. Wily's Apprentice Nov 15 '10 at 15:27
  • "However, I detest wasting vertical space." On one hand I agree with you. On the other hand I think that a method that takes more than 40, 50 lines (and therefore does not fit in an editor window) is too big / is doing too much and should be split. – Giorgio Jul 27 '12 at 16:22
  • "I’m a sloppy programmer" hmm... – Aram Kocharyan Jan 11 '14 at 01:32
19

I go with the second. It's more succinct and less verbose.

I try not to write to the lowest common denominator, so I expect that other developers know how to write one of the single most common control flow structures in programming today.

Steven Evers
  • 28,200
  • 10
  • 75
  • 159
16

I'd use the following (the consensus here):

if (condition) {
    any_number_of_statements;
}

Also possible:

if(condition) single_compact_statement;

Not so good, especially in C/C++-like languages:

if(condition) 
    single_compact_statement;

(No choice here in Python ;-)


In Perl, you'd use:

$C = $A**3 if $A != $B;

or

$C = $A**3 unless $A == $B;

(This is not pseudocode ;-)

Peter Mortensen
  • 1,050
  • 2
  • 12
  • 14
rubber boots
  • 371
  • 1
  • 7
  • 1
    My thoughts exactly. If the single statement looks good on a single line after the `if` clause, I don't use braces. For any other `if` statement (or any statement that uses multiple lines), I always use braces. In particular, if there's an `else` clause, each case always has braces. – eswald Nov 03 '10 at 17:33
  • 9
    I've never seen somebody confuse perl with pseudocode before. Random characters yes, pseudocode - no. – Joe D Nov 03 '10 at 20:24
  • 3
    I wonder if anyone's made a Perl program generator just by hooking up /dev/random to a Perl interpreter... – Christian Mann Nov 06 '10 at 07:40
  • I like ruby's approach here. It offers the perl style single-line ` if ` or a multiline block style `if ` / `` / `end` (ruby avoids braces, so here the opening brace is implied by `if` and the end brace is replaced by a literal `end`). It doesn't even offer the weird multiline-but-really-just-single-line if statement. – Ben Lee Dec 30 '13 at 23:33
  • The one-liner does not work with most debuggers (it is not possible to trigger a break when the content of the 'if' clause is about to be executed). – Peter Mortensen May 31 '14 at 18:52
11

I use the braces method - for all the reasons above plus one more.

Code merges. It's been known to happen on projects I've worked on that single-statement ifs have been broken by automatic merges. The scary thing is the indentation looks right even though the code is wrong, so this type of bug is hard to spot.

So I go with braces - on their own lines. It's easier to spot the levels that way. Yes, it does waste vertical screen real estate and that's a genuine downside. On balance though, I think it's worth it.

10

No braces. If some other programmer adds a second statement to my code it's no more my fault than if I let someone drive my car and they went over a cliff.

Peter Mortensen
  • 1,050
  • 2
  • 12
  • 14
Covar
  • 733
  • 1
  • 4
  • 15
  • 3
    Exactly! It's not our fault he/she doesn't know the syntax. – kirk.burleson Nov 11 '10 at 03:44
  • 3
    Bad example. A good one is a car with misplaced pedals - gas instead of brake. It's your car, so you don't care about anybody else. It's there problem that they don't know about your unique positioning of pedals. Are you a good car engineer in this case? – yegor256 Jan 30 '13 at 14:33
  • It'd be your fault if you gave them your car knowing they may be drunk. Similarly we should try to assume as little as possible about future developers to help ease maintenance. – Aram Kocharyan Jan 11 '14 at 01:35
8

We have had this argument more than once here, and the overall consensus is to always use braces. The main reasons are about readability/maintainability.

If you need to add code to the if block, you don't need to remember/search for braces. When future programmers read the code, the braces are always unambiguous.

On the plus side, ReSharper will automatically add the braces for lazy programmers in Visual Studio, and I assume there are addons for other IDEs that will do so as well.

Peter Mortensen
  • 1,050
  • 2
  • 12
  • 14
shimonyk
  • 141
  • 3
  • 3
    I categorically don’t buy the readability claim. Python is one of the most readable languages there is and it doesn’t need delimiters. That claim is just not true. I also don’t buy the maintainability claim because it’s so far unproven and still repeatedly rehashed. But in this case I’m actually very interested in empirical evidence. This is something that a study could very easily find out, and settle once and for all. – Konrad Rudolph Nov 03 '10 at 16:42
  • As Python uses indentation instead of delimiters they are implicit its not a valid comparison. – Murph Nov 03 '10 at 20:57
  • @Konrad - empirical evidence: When I was a new programmer I personally added code to an un-braced if block without realizing that the previous programmer had not bothered with braces. I have personally seen other people do this with my own eyes. Granted, only once did I see someone need help to find the problem after running their code, but that had more to do with bad testing skills. – shimonyk Nov 04 '10 at 13:14
  • @shimonyk: so basically your observations support my assertion that this problem is inconsequential? By the way, personal observations are anecdotes, they don’t count as empirical evidence. – Konrad Rudolph Nov 04 '10 at 13:17
  • @Konrad very well, please cite your sources also. I assume you have a peer reviewed double-blind study that you are referencing? If not, than merely flouting your own anecdotes in an attempt to prove others wrong while demanding other poster refer to 'evidence' is hypocritical at best. As someone further down on this very topic wrote "the onus here is on the opposition to prove their claim, not on me to disprove it". – shimonyk Nov 04 '10 at 13:31
  • @shimonyk: I wrote that and since you’ve read it you already know what I’m going to answer here: I don’t have to provide evidence to disprove your claim, that’s not how empirism works. *You* have to provide corroborating evidence. – Konrad Rudolph Nov 04 '10 at 13:41
  • Am I the only one who is'nt really interested in whether there is braces or not? I just use whatever VS puts there. – Nobody Nov 05 '10 at 14:18
7

I use the first syntax, almost without exception. Because it cannot be misinterpreted.

"Don't make me think" doesn't just apply to user-interfaces, y'all ;-)

Steven A. Lowe
  • 33,808
  • 2
  • 84
  • 151
5

I personally prefer the second. The first one looks ugly, awkward, and wastes horizontal space. The main problems with the second one are macros and people modifying your code at a later point getting it wrong.

To this, I say "don't use macros". I also say, "indent your damn code correctly". Considering how every text editor/IDE used for programming does indentation automatically, this shouldn't be that hard to do. When writing code in Emacs, I would use the auto-indent to identify if I wrote something wrong on a previous line. Anytime Emacs starts screwing up indentation, I usually know I've done something wrong.

In practice, I end up following whatever coding convention has been set before me. But these ones annoy me (and makes me much happier when I code in Python and this entire bracket disaster is gone):

if (condition) {
    statement;
} // stupid extra brace looks ugly

Then

if (condition) // the brackets have now just become noise
{ statement; } // also can't see the indentation, harder to read

Although honestly, two statements in an if statement annoy me far more than a single statement. Mostly because then brackets are required and it still looks funny with only two statements in the if statement.

jsternberg
  • 1,531
  • 11
  • 15
  • If you're going to write macros you should write them to make sure they can be inserted into any part of the code without breaking anyway. – Covar Nov 05 '10 at 19:01
4

I use the two-line version without braces (the 2nd form), but not to save space.

I use that form because I find it more readable, more visually appealing, and easier to type. I only use that form if those conditions are met; i.e. the if condition has to fit nicely on a single line, and the corresponding statement has to fit nicely on the following line. If that is not the case, then I will use braces to improve readability.

If I use this form, I make sure that there is an empty line (or a line containing only a brace) before and after the if statement (or above the comment, if present). While this is not a rule that I consciously follow, I notice it now after reading this question.

Conserving screen space is not a priority for me. If I needed more space I would use a larger monitor. My screen is already large enough for me to read anything that I might need to focus my attention on. It's unlikely that I would need to focus on so many lines of code at one time that they take up my entire screen. If there is so much nesting going on with a chunk of code that I can't understand it without viewing more of it at one time, then I would have to consider whether the logic could be better represented by refactoring.

Below are some examples that demonstrate how I use this form of the if statement.

    string GuardConditions(Plan planForWorldDomination)
    {
        if (planForWorldDomination == null)
            throw new ArgumentNullException("planForWorldDomination");

        if (!planForWorldDomination.IsComplete())
            return "Doh!";

        planForWorldDomination.Execute();
    }

    void ProcessingLogic()
    {
        OneBlankLineAbove();

        if (simpleCondition)
            simpleStatement();

        OneBlankLineBelow();
        OneBlankLineAbove();

        // optional comment on the line above an if statement
        if (simpleCondition)
            simpleStatement();

        OneBlankLineBelow();
    }

    void Assignment(string drive)
    {
        OneBlankLineAbove();

        string prompt;
        if (simpleCondition)
            prompt = "simple assignment";
        else
            prompt = null;

        OneBlankLineBelow();
    }

    string Return()
    {
        OneBlankLineAbove();

        if (simpleCondition)
            return "simple return";
        else
            return null;

        OneBlankLineBelow();
    }
3

Braces. Always. I'm kind of the fan of them, because it gives code some consistency. And also as @dsimcha wrote - less chance for errors on adding additional lines of code.

"Ugliness" of braces around single line of code are less harmful than additional work which is probable in those cases with debugging and/or adding code.

Peter Mortensen
  • 1,050
  • 2
  • 12
  • 14
  • 1
    I've never seen anyone make the error you're speaking of. – kirk.burleson Nov 11 '10 at 03:51
  • 1
    I've just made it yesterday on someone elses piece of code. :-) I just wonder how the upstream will look on, among other additions to the code, adding braces on all of his if's because he really seems to be from different side than me on this. :-) (calm down, I'm joking, edited just what I had to...) – Vedran Krivokuća Nov 11 '10 at 13:37
2

Personally I go with brackets.

Why?

Well if anyone comes along and needs to add code into the if statement it's 100% clear where the scope is.

It keeps the format of if statements consistent no matter how many statements there are in the block.

However, if the project style is to go without, stick to that.

ChrisF
  • 38,878
  • 11
  • 125
  • 168
1

I prefer braces for consistency, but not wasting too much white space (so more readably formatted code is in my limited field of view). So I write this for short enough lines:

If (cond) { statement; }
hotpaw2
  • 7,938
  • 4
  • 21
  • 47
1

I almost always use the brackets just to be on the safe side. However, sometimes if the contents of the block are really short I'll do leave them off and make it a one-liner like so:

if (x==5) Console.WriteLine("It's a five!");
JohnFx
  • 19,052
  • 8
  • 65
  • 112
  • Guess someone isn't a fan of brevity. – JohnFx Nov 03 '10 at 15:30
  • 2
    Brevity for sake of readability? Absolutely not. **It's code, not a golf contest.** – Josh K Nov 03 '10 at 15:39
  • 3
    I think readability is a great reason for brevity, personally. In any case: White-space doesn't count in my code-golf rulebook. – JohnFx Nov 03 '10 at 15:58
  • The one problem with this is it lends itself to abuse – Conrad Frix Nov 03 '10 at 21:32
  • 2
    Then don't abuse it. I'm not saying use it as a coding standard. There just happen to be a lot of times when you have a really short conditional followed by a really short single statement and this works well. For example an if (assert) log.write("assert failed"); – JohnFx Nov 03 '10 at 21:42
  • The whole point of this question is indeed that braces can make readability horrible when the action is short. So +1 for JohnFx. – Pierre Arlaud Nov 29 '13 at 09:58
  • The one-liner does not work with most debuggers (it is not possible to trigger a break when the content of the 'if' clause is about to be executed). – Peter Mortensen May 31 '14 at 18:52
0

I usually use braces, but there are some cases where I don't.

object GetObject() {
    // calculate obj1
    if(obj1 != null)
        return obj1;

    // calculate obj2
    if(obj2 != null)
        return obj2;

    // calculate obj3
    if(obj3 != null)
        return obj3;

    return defaultObj;
}

To me, it would just be silly to add them there. If someone adds a statement after the return, we have bigger problems than scoping issues.

0

If the IDE has code formatting available I do not use braces.

On the other hand, where code may be edited in other editors which does not support auto formatting it is dangerous not to put braces as mentioned in other posts. But even so I prefer not to use braces, and it has not been problem for me.

Peter Mortensen
  • 1,050
  • 2
  • 12
  • 14
nimcap
  • 623
  • 1
  • 5
  • 12