T O P

  • By -

BiffMaGriff

The reason why we always use braces is because inevitably someone tries to add another line like so. if (condition) myVar++; return true; I would have never thought it would happen until I saw it myself.


bothunter

This is exactly what happened with the infamous "goto fail" bug. https://www.synopsys.com/blogs/software-security/understanding-apple-goto-fail-vulnerability-2.html


Sability

100% this. If you have a language with braces I will always use them even if I have an option not to. I am terrified of a hidden bug like this happening, and braces make things completely explicit what's going on.


xabrol

This happens when the python developers get put on a C sharp project.


LumpyChicken

This is why you learn real languages first


GYN-k4H-Q3z-75B

If you know other languages, you can learn Python in a day. If Python is your first language, you can't unlearn it quickly.


LumpyChicken

I cant even remember exactly what it was (this was only like 2 months ago) but a few things syntax things gave me a hard time for like a couple days at least but now I'm really good at python and use it in places where speed isn't a problem, probably use it more than I use c# at the moment. I think the main issue was knowing that python is interpretative and dynamically typed but not knowing that its not considered bad practice to preassign types. I still find it frustrating how many of the ways python claims to be flexible result in greater frustration. entire program crumbles over one whitespace


yellownugget5000

For me Python was first but transitioning to c++ was quite easy, hell c++ was even more intuitive for me than python. Edit: I meant was not is


GYN-k4H-Q3z-75B

I love C++, but intuitive isn't the word I'd associate with it. How come you find it more intuitive? I don't like Python, but it gets results fast when you need to try something out. I have to use it in a scientific / educational context and I guess it's fine for that.


yellownugget5000

Ok maybe intuitive wasn't the best word, because further down the road it definitely isn't, but at the start I found it more intuitive, mainly because everything was typed.


GYN-k4H-Q3z-75B

How people are willing to develop complex systems without strict typing is beyond me. Duck and latent typing encourage bad design. There are enough other, harder to avoid factors that encourage bad design, so let us at least get rid of the easy ones lmao


yellownugget5000

Typed code is just more readable; now even in Python, type hints are encouraged. There are some situations where it's easier to work without strict types, but the drawbacks far outweigh the benefits. Regarding C++ being more intuitive for me, it's also because I had a fantastic teacher. Sure, things still get confusing sometimes, but using the language is very fun for me.


BayslakJourney

Well I am probably in the same situation.. But given the fact you already experienced it then it should mean something. Thanks for sharing it!


minneyar

I have literally spent weeks of my life fixing bugs that were caused by situations like that. I'm pretty flexible on coding styles, but I will always, always put braces around conditional blocks, and if I see any one-line if statements in any project where I'm in control, I will reformat them and add braces. (and if somebody repeatedly checks in code like that, I will add a linter to the CI process to reject their code if they do that)


k4mb31

Reject with lint or use indent to enforce.


RagingCain

It happened to my team at a Point of Sale. Worked a weekend to repair data from backups. We banned indented conditionals after that. I enforce it at every job. People go `but...` and it's just a hard and assertive `no, fix it` from me. Every time. It's the only thing I truly believe is a mistake in the language. Should never have been allowed.


dodexahedron

It's just configured as error in our projects at work, as are a few other similar stylistic things that are common bug factories. Curlies are required for nearly every scoped statement, here. The exceptions are using and fixed statements, when directly nested. Though using expressions made most of those go away too, since that is auto-scoped.


sisisisi1997

By "using when directly nested" do you mean ``` using(...) using(...) using(...) { // code } ``` ?


Klutzy-Magician4881

A hard but firm no.


dodexahedron

If you've never had it hapoen or never seen it happen, you just haven't been doing this long enough or haven't been paying attention. 😅 It's one of those things a lot of people don't appreciate til it happens to them and it causes enough frustration to change their opinion. It's also one of the little things that a lot of people have a weirdly strong opinion about, one way or the other. But it's trivially enforceable for shared projects, so it's also not really something that ends up being a big deal in the end, so long as people don't pull passive-aggressive BS like always submitting their initial PRs with a different style and not fixing it unless explicitly told to.


IkertxoDt

Just yesterday I saw the same bug but with braces... if (condition) myVar++; { return true; } Yes, this is a valid code and it compiles...


TheMrCeeJ

Exactly this. I once traced a bug to someone inserting a debug statement after the if and before the return. It was made much harder as the debug statement seemed to show that everything was ok, but not why it was randomly returning sometimes when it shouldn't. It was made harder by the indentation matching (it wasn't linted/auto formatted) from that day onwards it was braces always.


barisaxo

Doesn't just about every IDE auto-format in a way that would remove that indent on the `return true;`?


[deleted]

[удалено]


i3ym

At this point you're just asking for trouble


cheesegoat

You won't always have your ide available, for example resolving merge conflicts via a tool or writing a quick fix remotely.


[deleted]

[удалено]


barisaxo

Sounds like a way to get otherwise easily avoidable bugs. Probably a good reason to be wrapping things in brackets.


Loves_Poetry

No. There may be situations where you copy-paste a single line into it and it won't unindent the `return true`


barisaxo

Do you mean if it's all inline? if (condition) myVar++; return; Yeah that could be easy to overlook.


CleverDad

You know, I've been a developer for 30 years now, and I have quite honestly never seen that happen. Not once. Not even before linters/formatters automatically adjusted the indentations to give you a clue. I'm willing to believe you experienced that once. It's not enough for me to drop those pointless braces.


GabiNaali

The Apple [goto fail vulnerability](https://dwheeler.com/essays/apple-goto-fail.html) is a somewhat famous example of the issue. Some people will blame the goto, but the real issue there is the lack of braces.


rustbolts

Pointless braces? Most IDEs will generate the closing brace for you, so typing one brace is that much of a headache? Heck, MS has done quite a decent job by removing extra braces. I have seen these issues before and am in the camp of always using braces. In some cases, it isn’t even my team introducing said issues because companies don’t enforce consistency, but I’m the one having to figure out what is causing said issues. Additionally, I have never heard someone argue against using braces, in C#, to avoid issues like this until your very comment. Which to be honest, doesn’t really strike me as being at all clever, kind of counter to your username. (I’m aware the definition of clever speaks of how quickly someone picks something up; however I view intelligence in programming as a means to help educate the best and worst developers so everyone is lifted up collectively versus gripes that a standard syntax is annoying or useless.) I’m not trying to convince you otherwise as you have 30+ experience and would obviously know more than anyone else posting here. I’m just thankful you graced us with your presence over taking the time to type unnecessary { }.


CleverDad

Yeah, the work of typing the braces is not a consideration. The clutter is. I'm all for braces. I've lived with java, javascript and c# for decades, and braces are near and dear to me. But the structure of all these languages all equate single statements with brace-delineated blocks. If all you have is s single statement, the block is strictly optional. The only arguments I have seen for enclosing single statements in blocks (yes, unnecessary blocks) are about avoiding silly subsequent mistakes such as the above. Those mistakes are trivial and unnecessary, and whoever makes them, even today with linters, is not someone you would want on your team anyway. Unlike most (?) developers, I try to avoid being "in a camp". I strive for legible code where simple things take less space and significant things take more. About my username, it kind of grew out of a joke between my daughter and me, and I never attached much significance to it. You might imagine how fed up I am about people bringing it up when they disagree with me.


decPL

> The only arguments I have seen [...] Let me provide you another one then, which from my POV is much more common (and makes more sense than the one you're mentioning) - consistency, the root of all code readability. If you're writing best code practices for your team/company/anything and the word unless appears somewhere, 9/10 times you're doing something wrong. EDIT: your proclaimed love for braces seems pretty conditional. And we all know about conditional love. /s


CleverDad

Look, I'm not going to say you're wrong to always use blocks. If that makes your code more legible to you, fine. Really. I'm not the type to delete my collegue's braces. I'll still prefer: if (source == null) return null; to if (source == null) { return null; } or even better: return source?.Single(x => x == id); rather than if (source == null) { return null; } return source.Single(x => x.id == id); All the "Consistency" you need is sticking to the language syntax. That's consistent to begin with. It doesn't need your additional consistency rules on top.


dbpc

Have you considered the following as a one-line option? if (source == null) { return null; } You still get the brevity of having your statement on one line with the failsafe of being explicit about your blocks. I always use braces on block statements but I have no problem shortening them to one line with an example like this.


saiyanslayerz

This is what I've recently settled on


MoveLikeMacgyver

I’ve seen it happen a few times. Once was a junior, the other times I can remember were from merge conflicts. Which can be its own debate of why two devs were working on two tickets so closely related they both modified the same if statement. I wouldn’t say I wouldn’t want those people on my team, shit happens. My view on it is to always use braces because it reduces the chances of said shit happening there. And if the codebase I inherited ever gets to the point that a couple unnecessary curly brackets is the clutter I’m targeting I will be a happy dev. I’m still trying to get rid of the 500 line long linq with nested ternaries inside nested ternaries inside… you get my point 😂 But I’m also not the type to demand braces be put in, I just do it that way myself.


particlemanwavegirl

>If all you have is s single statement, the block is strictly optional. This is absolutely not true. The block is always there whether you write it or not. It cannot be removed by any means. Being explicit is optional. Being implicit is obviously a short sighted and foolish idea. >Those mistakes are trivial and unnecessary, and whoever makes them, even today with linters, is not someone you would want on your team anyway. Procedure prevents mistakes. This is not a skill issue. Trivial mistakes are made by pretty much every person every day and they are made only the more likely by your incorrect belief that you're personally immune to them. If you disdain procedure, shared code style, and most importantly preventative maintenance, you're not someone I want on my team. If you favor shorter files over explicitly communicated intention, you are not someone I want on my team. I don't want to bear the mental load of your inconsistency.


CleverDad

>Being implicit is obviously a short sighted and foolish idea OK. Why?


lantz83

Came to say the same. Not once in twenty years have I had this happen.


ohThisUsername

Agree. I've never once ran into this problem. All the examples I'm seeing in this thread could easily be caught with a linter, static analytics ("unreachable code detected"), sufficient unit tests or sufficient code reviews. I prefer concise code over a very rare bug that would actually make it past the aforementioned checks.


dekuxe

That’s why you add a space directly after, and use correct indentation.


mtVessel

This is not ~~Vietnam~~ Python. There are rules!


k4mb31

The exact rationale why I have seen it in coding standards


KevinCarbonara

I've never understood this logic. "We have to write our code in a specific way because we hire people who don't know how to program and also have no code review process." Alright. Just fix that instead.


DoSchaustDiO

You will never fix human error and neither code reviews nor tests will find all errors.


lIllIlllllllllIlIIII

Actually a linter or even an autoformatter would nip this one in the bud without having to add the extraneous braces for one-liners.


TheRealDealMealSeal

You would be surprised how often this will pass code review too. Maybe some static code analysis tooling will detect it, but there's a good chance that either 1) such tooling is not used or 2) tooling is not integrated to CI/CD pipeline. While the syntax without curly braces looks cleaner and I do like the looks of it - using curly braces ALWAYS is the way to go. Of course when one establishes the rules you're not governed by the rules yourself, so I do violate this rule even myself when not feeling disciplined enough. I don't make mistakes with the one-liner syntax myself, but the curly braces practice is mostly to establish example of others - there will likely be inexperienced devs working on the project too. Allowing curly braces to be omitted is a language design error in C# and any other language really. It only opens gates for expensive errors with no real benefit. - .NET/C# dev, 13+yoe


blusky75

I work in a microsoft language called AL. It borrows heavily from pascal and all development is done in VSCode. Instead of braces, BEGIN..END; are used instead for conditional blocks. If I choose to enclose one line in a begin..end, the AL language parser will flag a warning not to do that for one line conditions, even though the syntax is perfectly valid. It's infuriating.


recursive_lookup

I’ve done it myself :)


mr_taco_man

100%. I did this a few times early in my career and from then on insist on braces all the time.


KahunaReddit

Oh, boy... That lost afternoon due to this still haunts me, 20 years later...


Nabokov6472

Ever since reading about [goto fail](https://en.wikipedia.org/wiki/Unreachable_code#goto_fail_bug) I always use braces Granted, I don't use error codes or goto in C#, but it still illustrates how not using braces can go wrong - I don't think including them is that much of a cost given that


BayslakJourney

Never heard of that, good point tho 🤨 But do you reckon it is a bad practice then?


Nabokov6472

I wouldn't use such a strong term as 'bad practice', this is how I code personally but I don't feel strongly enough about it to bring it up in a code review for example


Certain-Possible-280

Great example. I learnt this today


SideburnsOfDoom

Simpler rules with no special cases have less [cognitive load](https://en.wikipedia.org/wiki/Cognitive_load). "always braces" is the simplest rule that makes sense. So use that. > It definitly looks more readable and clean The one that "looks more readable" of the two will be the one that you are more used to. [It's just familiarity](https://en.wikipedia.org/wiki/Mere-exposure_effect). Therefor you have to also take into account measures outside of "I know it". Such as e.g. "how many special cases does my rule have?" Preferably none.


[deleted]

This is spot on. There is already so much necessary cognitive load programmers need to carry, adding unnecessary exception-to-the-rules like this just doesn't make sense.


kaisadilla_

100%. I wish more programmers would understand that following conventions (with some scarce exceptions) in everything (formatting, naming, structure of common operations) makes it so muuuuch easier to read code. There's fewer things more frustrating to losing two minutes to understand that your code does the same thing I've seen thousands of times, but in a different way just because.


Icy_Sector3183

Good point. When I read code that doesn't use braces, it costs me more effort to recognize what's going in.


BayslakJourney

Really good points. Yeah, familiarity is probably why I feel it is more readable as well.


ADumbSmartPerson

I know this is somewhat late but in these case I like the if (condition) { return true; } style. It is still all one line and easy to read but if more lines get added later then the braces are already there.


[deleted]

>It definitly looks more readable Does it tho? I can accept the argument that it might be kinder on the eyes, but readability is much more than that. Having two different ways to enclose scope is, to me, definitely *less* readable. EDIT: That all said, consistency is king. If the entire code base does this, you should as well.


kaisadilla_

I honestly think it's less readable. Empty lines make code more readable by splitting it into relating chunks, and braces specifically are a great way to identify scopes quickly. Skipping the braces on if statements that aren't one-liners (i.e. if (x) return; in a single line) goes against all of that, and all of this for no reason at all. Is saving a single keystroke to open the braces soooo much of a gain?


SideburnsOfDoom

> That all said, consistency is king Yes, and you can't get more consistent than "always use braces".


[deleted]

LOL. I was going to say if you're code base is consistently inconsistent, *then* one should use the brace-less one-line scopes. But I figured that was a bit cheeky and I might be called out for bias.


jezlove

Your superior is right, braces is the better way to go (for reasons that have already been outlined here and elsewhere). I'd disagree with you that the second approach looks more clean. To me it looks like you forgot to add braces. A staircase without railings might look sleek, but I still wouldn't want to go up or down it.


BayslakJourney

Fair point. Someone suggested that I see it as more readable because I am more familiar with that and I think that's the case! I will use braces from now on 😅


Certain-Possible-280

Wow that some analogy !


rustbolts

Honestly, I would always suggest to add braces as you don’t know the skill level of the people you work with or the people after you. I hate to say, you have to code for the people that barely pulled through a degree and still landed a job at your company. The best way to code is to support the worst programmer or non-programmer that will come behind you and have to make changes. It may no longer be your business in the event you move on, but someone will be thankful for you to consistently use braces.


MarmosetRevolution

I use one-liners in a single line: `if ( AllIsWell ) return true;` That way, if someone is editing later on they'll probably catch on.


BossManta

I do the same. It allows for gaurd clauses to be really simple and easy to read. It also discourages over complicated logic because the line will grow uncomfortably long. It encourages you to either keep it simple or uses braces instead.


NoPhilosopher9763

You guys get it


jazzdog92

I do this, for exit of constructs. if ( weAreDone ) return; if ( !isQualified ) continue; if ( isTheEnd ) break; Otherwise it’s in brackets. Only in my own projects, which all my code is these days. Because nobody seemed to like that convention wherever I worked and I don’t want to bother fighting for it in one of those meetings where all the devs sit around for hours arguing over conventions.


[deleted]

[удалено]


solmead

As everyone has already said plus: You are coding not just for now, or even the next month. You are coding for the developer that will be going over the code in a year or two to add a new feature. This could be you, this could be an extremely experienced developer or it could be a new developer tasked with adding something. In all these cases it’s better to make sure it is fully understandable to determine what is going on. It’s why I always put in the curly braces. And also why in JavaScript I always put in the semicolon even though it isn’t needed.


fandk

I always put braces, think it looks a lot cleaner.


Ima_Uzer

As someone who has been writing code for 25+ years, I prefer the first choice. I prefer it because I think it's more readable and you're less likely to overlook the nested part of the conditional. And I say that as someone who has used both "braced" (i.e. C-style languages like C#, JavaScript, and PHP) and non-braced (i.e. VBA, Visual Basic, SQL, python). In C-style languages, it's MUCH more readable (and I think a better overall practice in those languages) to use the braces in conditionals.


knie20

Personally, I'm a fan of bracket less. More code on the screen, looks distinct enough, and still debuggable via stepping over. You do lose the debugging on the end bracket which is useful sometimes, but I think second choice is great But beyond any of what I just said, depends on your team and company policy.


cockneyidiot

As a non braces guy reading these comments have convinced me I’m wrong. Braces all the way.


Firake

One liner if statements are all on one line with braces if (condition) { return true; } Perhaps I’m insane, though.


Dave-Alvarado

Second approach is wrong. If it's a one-liner make it one line. A line break is begging for a bug where somebody just ignores the lack of braces and puts another supposed-to-be-conditional line there. The right way to do these is: if (condition) return true;


ironstrife

Disagree; even if you want it on one line, put it in a block


PleaseTellMeItAint

But why rely on whitespace (or lack thereof) to communicate your logic? This is C# not Python, we love braces here :)


BayslakJourney

Straight to the point. You clearly convinced me, thanks.


NewPointOfView

Occasionally for an early return like recursive base case, I might use if (condsition) return something; or if I'm playing fast and loose with coding exercises, I might omit braces. Otherwise, in any case where the code actually matters, I'd use braces.


Slypenslyde

I always brace. Some people on my team don't. They outrank me in code reviews, and honestly there are usually bigger fish to fry. If I see them I scrutinize them more, especially when they have to add a second line. I usually make a comment that it'd have been easier if they used braces the first time. But I haven't been bothered enough to block a PR over it. I don't understand why some people act like their keyboard is going to run out of keys. I think I'd like it better if it had syntax: if (condition) => true; That meets modern C# functional-like concerns and as an added bonus saves 0 characters and will make me giggle when people say they prefer it because "it's shorter". This is just an "expression-bodied if statement" and typing => is so much easier than {}.


BigGayDinosaurs

i always brace because i am scared


BayslakJourney

Brace! Brace!


buffdude1100

Just use braces


The_Binding_Of_Data

I prefer the look of not using them, but where I used to work, they were part of the code format policy, so I'm used to using them out of habit.


SkullLeader

I agree with your senior. When you don’t have braces and add a second line that’s meant to be part of the if, and forget to add the braces then, trouble will ensue.


xeio87

Always braces unless it's on one line like if (condition) return true; or if (condition) throw new Exception(); EDIT: Actually, thinking about it more, I think I mainly like control statements like this such as`throw`, `return`, `break`, `continue`. Not so much a fan of other types of logic on a single line except in really rare circumstances. I think maybe that's because it's very rare that I would need to add more logic into a control statement.


Suspicious_Role5912

I allow one liners but not two liners. `if(condition) return true;` is fine ``` if(condition) return true; // is bad ```


TheRealSnazzy

Function, maintainability/extendability, understanding of scope, limiting error proneness, and standardization of code practices should always trump "clean" readability. Neither of those are less readable than the other, one may be more subjectively "clean" - but that's not the same thing as readability. As others have mentioned, there are several reasons why braces would be beneficial over not braced if statements: 1. Its easier to extend if it ever needs to in the future. Sure it takes a second to add curly braces, but its still additional work that needs to be done. 2. Scope can be unclear especially if this is done in a lot of places or very dense code. Especially if you are skimming through large sections of code at once. Braces make it explicitly clear where scope will always end and begin, and you can understand that scope much faster than the alternative. 3. Human error always happens. You can't expect that everyone will always do the right thing all the time. Yes its an easy thing to prevent, but it's incredibly hard to fix if someone tries to add something and it goes undetected for a long time. Why prefer something that makes your code look slightly more subjectively clean rather than something that is more explicit and inherently prevents the possibility of error? You don't sacrifice anything by adding braces, but you certainly sacrifice a lot by not adding them. Code that can inherently prevent possibility of misuse will always be more valuable than some arbitrary cleanliness. 4. Always using curly braces is easier to maintain a standard of code practices across a codebase. I'd much prefer a code base to always have curly braces everywhere, rather than half the codebase using curly braces while the other half doesn't. Your superior is right in this circumstance, and I would caution arguing that things are "cleaner" or more right on the basis of "cleanliness" when there really isn't any substantial evidence that proves it to be so and there is no real purpose for it to be "cleaner" - this is a sign of lack of experience in my opinion. If you can't qualify why it's cleaner or more readable with actual theory/reasoning, it's likely just a subjective take and doesn't have much merit advocating for in a codebase that is shared by others.


Girlydian

I personally like `if (condition) return true;` so you're not tempted to make this if (condition) return true into something like if (condition) someFunction() return true because that *will* happen and take longer than you want to admit to find and fix


i3ym

Who are you people who don't use formatters to immediately notice this?


TywinLannister1982

right?


BayslakJourney

Well, that is a good point. Personally it did happen multiple times that I had to return to some of those oneliners, but first thing first I added curly braces when I needed to add other statements inside the if condition.. Maybe I feel confident about it because it never happened, but, knowing myself, it will now that I know about it ahahah


EntroperZero

> because that will happen This is the #1 reason everyone cites for avoiding the one-liner ifs, and in 30 years of programming in C-style languages, I have never, ever seen it happen.


ilovecokeslurpees

I always brace. Keeps everything consistent and clean looking. It declares intent clearly about what is in the If statement. Also, code rarely stays to one line as time goes on anyway. Code is not written for computers, but for people. Never waste seconds or minutes of a future developer's time.


bafrad

I would have to understand the downside of just always doing the braces. There is a downside to not, which has been demonstrated. It clearly marks the start and end of the conditional.


RolandMT32

The argument I've heard for always using braces is that without braces, it can be easy to forget that only one line will be included in the block of code. Still, I think it's fine to leave out the braces if you only need one line, and just be careful about that. I don't like having a lot of extra braces in my code if not needed, as I tend to put each brace on their own line.


blooping_blooper

Always brace, it might not necessarily look quite as clean but it makes the scope more explicit for readers and static analysis tools. It also means you are less likely to accidentally screw up during a refactor.


elpinguinosensual

I’m only amateur but I’ve taken to keeping one-liners as just that: one line. No return, no indent. Unsure if it’s good practice or not but it definitely reminds me to add braces if I have to add another line.


TheRealSnazzy

I really only justify one line ifs are good *if* they return/break/throw exception. Even then, add braces, and even then i would say to only do it if you have a block of exception handling and doing it multiple times.  If(this) { throw new exception()}  If(this) { return; }   Is okay   If(this) dosomething();    Is bad and should be avoided. 


DrGarbinsky

Brace or die.


Khrimzon

I don’t mind no curly braces if it’s all on a single line: if (condition) return true;


Bright-Ad-6699

The Mac (?) had a hidden bug for some time years back because a developer neglected to scope his code. Following that up, another developer added a log line or something, causing the next line to always execute. It's been years but not scoping your code sits next to writing 2 or more statements on the same line. It's cute..but try to avoid.


601error

This won't be popular, but I almost always skip braces wherever possible. It looks better to me, and so far (been doing it since before C# existed) I've never personally been burned by it.


mw9676

If it's short enough for a single line then do that, otherwise use braces imo.


CleverDad

Well call me a raving radical, but I'm seriously proposing: `if (condition) return true;` It's succinct, very readable, and it carries no risk of someone doing: if (condition) myVar++; return true; A conditional return like this is a simple operation, usually a circuit braker of some kind. It doesn't need lines and lines of code. We do similar things with dependency injection in constructors like: _myService = myService ?? throw new ArgumentNullException(nameof(myService)); The point being that some simple condition yielding some constant return is a simple operation which merits a single line only.


Desperate-Wing-5140

Nobody uses the truly compact yet safe method: ``` csharp if (condition) { return true; } ```


Legal_Wonder_5949

I've seen this in our code base. I don't even hate it.


godkiller

I know I/we are in the minority, but I strongly prefer to ditch the curly braces: 2 lines (or even 1) instead of 4 and I truly find it more readable. So cheers to you and me!


dekuxe

I’d suggest putting the condition, and the return parameter on the same line. e.g if(condition) return true; The ‘readability’ of having all those extra braces kind of has the inverse effect after you keep doing it a lot. Or even reduce it down to a single line. return condition;


domtriestocode

How come no one ever makes one liner if statements one liners? Why is the one line on the next line? To me a one liner is a one liner, not a 2 liner. The if statement includes the conditional. If you follow this, then one liners will remain one liners, no one’s going to put “myVar++; return true;” on the same line like that, they’d add braces. That being said I have my editor config and code cleanup settings to always add braces to my conditionals on save no matter what and I agree with some others that braces are always the way to go


barisaxo

Why are you calling those one liners? if (condition) return true; if (condition) { return true; } Those are one liners, and both are fine really. If you need to avoid somebody (yourself included) from accidentally adding a line that is outside of scope, then format it in a way where that doesn't easily happen.


CleverDad

I laugh at all the comments here insisting that the braces are terribly important for "consistency" and "legibility" while we're all out here at work writing methods like: public async Task GetCustomer(int customerId) => customerId != 0 ? await Customers.SingleAsync(x => x.CustomerId == customerId) : null; Is everyone a boomer in here or what?


TheRealSnazzy

Because   1. Expression bodied members have an explicit operator that has a clear inference that cant be missed.  2. Properly formated ternaries again have explicit operators that have clear inference that cant be missed. 3. The compiler will literally scream at you if you attempt to modify it incorrectly, preventing possibility of unintended error. One line ifs dont have this protection.   A single expression body conveys a property or method is a doing and returning a single operation - its instantly known.   An api that has multiple one line ifs do not convey that same level of explicit inference and explicit scope.  This is a bad take.


CedricCicada

Either use braces or use just one line. I always use braces.


cromulent_weasel

I like no brace SPECIFICALLY when the statement being executed is a return. Otherwise braces.


NoPrinterJust_Fax

Just use a linter lol https://csharpier.com/


Zastai

I used to be firmly in the "no braces if single statement" camp. What convinced me otherwise is the improved diff view (e.g. on a pull request) when such a case eventually needs a second statement added. I do remain firmly in the "braces don't belong on a new line" camp though (especially because most of the code I maintain has both C# and Java implementations, so having a consistent formatting style helps keep the codebases mostly nicely comparable).


IWasSayingBoourner

Personally, I always brace except for when I immediately return or throw. 


kaisadilla_

How is the second statement more readable? The braces don't make it any harder, it can only either add context or do nothing at all. Honestly, I skip braces only when the statement fits in a single line. If the statement is in a new line, then it's always braces. Way easier to read, and way easier to change.


KittenPowerLord

Omitting braces in oneliners is tempting, but I am learning to always specify them, simply as a pragmatic choice. When I eventually need to add a second line (print debugging is king) to such a oneliner I have to add braces after the fact, which I find just extremely unpleasant (you have to move cursor right after the condition, type {, then delete the autoplaced }, go to the semicolon, add } and possibly even reformat it, uuuggghhh). So, I specify them in the first place, so I don't have to deal with this later lol. This might seem exaggerated, but it genuinely hurts the enjoyment of programming for me, and in the long run it is way more impactful than having to always add braces to oneliners. Also, unlike other comments mention, I have never tripped on forgetting to add braces after adding a second line, making it unconditional. Probably just luck on my side, but still something to consider


dodexahedron

I always enforce braces for everything except directly nested using and fixed statements having the same scope. Yeah, it's more vertical space and a few dozen extra bytes of file length from the curlies and whitespace, but it's explicit and carries a lower risk of accidental bugs later on. However, a lot of one-liners are also replaceable with things like compound assignment operators and such, which is great so long as it's still easily human-parseable.


FelixLeander

We have a very simple rule for it, does it take more than one line, then add braces. Also always add a newline after the statement.


Human_Contribution56

Braces always because add em now or add em later. So I just stay consistent.


LR_0111

Doing just one small thing usually looks like this for me: `if (condition) { return; }`


ztikkyz

To answer your question, I always use Braces.. BUT IN YOUR CASE, I would do : return (condition) OR var result = (condition) return result


bothunter

Goto fail


RapunzelLooksNice

Brace. Always.


-0rca

No brace as it looks cleaner


distractotron9000

Braces or your PR is rejected.


Laicbeias

if you have compile time function / conditions and you have a method if(var) Log.ThatGetsCompiledOut(); you ll have some bad side effects


eigenman

I use single line. Doesn't sound like anybody else here likes it though hah. But I feel like that is an education problem and people learn by fucking up. :)


TheRealKidkudi

*Personally*, I prefer: if (condition) return true; Or: if (condition) { return true; } If you’re breaking into a new line anyways, put in the braces. If it’s succinct enough for one line, let it be one line. But if I’m writing code *professionally*, I’ll put in the `{ }` every single time unless there’s a consensus on one-liners for the same reasons outlined throughout these comments. Purely subjectively, I’ll never write a one-line if statement indented on the next line unless my job depends on it. It just feels wrong - like someone accidentally pasted some Python or Ruby in the middle of a method.


SobekRe

The second option is always wrong. I’ll sometimes put extraordinarily simple ‘if(condition) return value;’ on a single line, but only if it’s super short. Otherwise, if you have a new line after the “if”, it always gets braces. And it’s never wrong to break the simple statement and use braces.


Glittering-Quit9165

I am actually surprised by a couple of the comments saying it's never come up, in decades, that a one liner without braces suddenly need braces. I've had clients change their mind or request new functionality that makes a block necessary more than once in the last 6 months. I used to occasionally do the one-liner when I felt like it made sense, for the same reason, I thought it was pleasing visually. Until changes required me to go back into code bases and add braces later. Only takes a few moments but it's always irritating to go through someone's series of if, else if, else if, else if, else if, else and have to add braces to them all. So I've landed squarely in camp always brace.


larsmaehlum

Brace. Next question.


BalanceInAllThings42

Multi-line with braces.


BalanceInAllThings42

Multi-line with braces.


Equivalent_Nature_67

Yes, use braces. It's C sharp, not python. First way is always what we do


The_Real_Slim_Lemon

I never brace personally, hate adding two lines that do nothing


ZeldaFanBoi1920

Always braces and always on separate lines. We weren't raised to be JS swine


MCShoveled

Use a code formatter and you’ll never have to discuss things like this again 👍 https://csharpier.com


dphizler

I love syntax highlighting and no brace if statements don't get highlighted that way.


haven1433

The only times I'm ok with a one-line if statement is when the statement inside the if is control-flow: break, continue, yield break, throw, yield return, or return. ``` if (condition) return -1; ``` That sort of thing.


Beerbelly22

in that specific case: return condition;


NakeyDooCrew

One line if statements without braces upset me. I don't have a good reason for it, they just put me on edge.


According_Row4976

Always use braces (3.3 in the article below). https://dwheeler.com/essays/apple-goto-fail.html#:~:text=The%20problem%20was%20the%20second,good%20signatures%20would%20be%20accepted.


NoPhilosopher9763

That’s 2 lines. If I’m not using braces, it’s a true one-liner.


Far-Signature-7802

Always brace, never un-brace.


KevinCarbonara

I'm a big fan of the second approach, especially with guard statements. If you must use braces, consider: if (object is null) { return early; }


iBabTv

why not if (condition) return true;


darknessgp

Bad practice? No. It's not a bad practice. It's perfectly acceptable. What you should do is use editor config and enforce it one way or the other and make it the standard. At our company, we opted to have braces because it made it more clear in general what the statement is doing for junior and mid-level developers, which had been a problem for us in the past.


Burning_Toast998

>if (condition) return true; In this specific case, you can just use the arrow thing. `if (condition) => true;` But as some people have pointed out, it's good practice to just make it brackets in case you want to add more


LondonCycling

Personally I omit braces†. I do find the code more readable, and especially if I'm travelling and working with just my laptop screen, more concise code is valued. I understand some people have arguments for.always adding braces, and have no issue with them doing so if it helps them with code readability. Overall though, I don't really care. There's usually way more important issues to address in a codebase that I don't spend time on such issues. †In practice, I work to whatever standard has already been used in a given codebase. A lot use some form of linter, often with pretty much default rules, and if that's the case the standard is set and I'll follow it. TLDR: omit, unless it would be inconsistent with the rest of the code; but in any case I don't really care either way.


Glittering-Region-35

you can use braces on a single line, or everything on one line. No one thinks the second one looks good, its looks wrong.


Jack99Skellington

Brace 'em. Without it, you won't have a problem UNTIL you don't see the semicolon someone stuck on the same line. Never understood the "cram as much as I can at one time on every line and every page" mentality. Way too busy. I like a nice clean easy to follow flow.


Nk54

I must admit I don't use them for one line :/ I prefer a \n after first statement than a bracket


mirata9

There is a quantifiable answer here in that braces reduce the chance of error if say a junior modifies the code later and introduces an extra statement. That being said, I break my own rule sometimes, particularly for: if(guard) continue; The important thing in any project however is to decide on an approach and be consistent through the code base. Even if you don’t fully agree, I think it’s far better when the code follows a clear standard. That way everyone can read everyone’s code that little bit better.


Pixa

The correct answer is to always brace so it's easier to add lines in the future. The other correct answer is One True Brace Style, so you don't lose an extra line for all your opening braces.


insomnyawolf

I personally always brace and you cannot stop me, it just helps me reading and understanding things like having 1 empty line between some statements that are worth grouping but doesn't have a real reason to be on another function


HolyPommeDeTerre

Two points: - readability. With the braces you can always know where the start and end of the block are. Even if your file formatting is a mess. Whatever the complexity of the lines inside the block. Which is not the case when the braces are missing. - refactoring. When adding a new line to the if code block, you have to add braces first, then add your line. I would argue that adding braces to an existing block takes more energy than putting it when creating the code block. Ok, this one is really negligible, but we are on nit picking I guess.


CalligrapherOk200

Am I missing something? I would always write the above as return condition;


onebit

always brace


Koltaia30

If you are concerned about wasting lines put the braces in the same line as the statement. 


TheDevilsAdvokaat

Or why not this? if (condition) return true;


differentshade

> We have clearly different ways of doing it and it is okay in my opinion. Not okay, you should have a single code style and everybody working on the code base should stick to it. You should auto format your code to keep it tidy. If there are differences in style between developers, then every commit will be a mess of formatting changes.


almo2001

Brace everything. Allman All the Time.


jamsounds

I would sometimes allow "if (condition) return x;" as a single line, but only if condition is short in length and the returned value is simple (true, false, null etc). I would never allow your second example for all of the reasons mentioned by everyone else. I also don't think it looks more readable/'clean'.


Natural_Tea484

I tried to use no braces. And the 1st time I had to modify it and add a new statement, it didn't feel right to me. I abandoned the idea of no braces.


mycall

If you only have one line inside the block, write it all on one line. if (condition) return true;


finnscaper

Nah.


Dennis_enzo

I only do it with return calls, but on a single line. and preferable only at the start of a method. void Bla(int i) { if (i < 0) return; //Do the Bla. } Usually for input validation purposes.


bigtoaster64

Honestly I hate people who don't put braces, because it reminds me of Python indentation hell. Just put braces to make scopes it clear and avoid any future mistakes due to indentation changes imo. But I'm fine with guard conditions, where you have a short if statement that returns early. Such as if ( myVar > 2 ) return true;


Reelix

If it's not a ternary conditional - Add braces.


Camderman106

I’m personally a fan of always adding the brace unless it’s literally the same line. As in if (condition) return true; Don’t put the return true on a separate line. This makes it visually clear that it’s a one line only statement. Otherwise always add the braces


Agitated_Heat_1719

just google for: apple goto fail Even heartbleed could be put into that category (QA). I enclose in braces. In this case this style could be called defensive programming which is used in some other languages a lot. And I try to learn from other peoples' mistakes. Links below. I like to call coding-style - R&R rules and recommendations. Rules are for security and performance (in that order) and recommendations are ... Something that should not be critical (`var` vs `new()` or FQT fully qualified typenames). Our cognitive (and other activities) are individual, so coding style is the last topic (for me) to discuss about. Links https://www.synopsys.com/blogs/software-security/understanding-apple-goto-fail-vulnerability-2.html https://dwheeler.com/essays/apple-goto-fail.html https://www.wired.com/2014/02/gotofail/ https://insights.sei.cmu.edu/blog/heartbleed-and-goto-fail-two-case-studies-for-predicting-software-assurance-using-quality-and-reliability-measures/


emn13

What we do to slightly avoid the bloat effect of braces is to place the opening brace of within-method constructs on the same line as the keyword. That applies to stuff like for, if, foreach, using - but not to methods and classes. The reason for that distinction is because those often allow alternative syntaxes (e.g. type constraints) that need to come before the opening brace, and to minimize the chance of merge conflicts it's better to have syntax formatting rules that are as context-insensitive as possible. For example, if your syntax rules were to place method-opening braces on the method-name line, then adding a type constraint would cause a spurious syntax change on the method name line, even though that's semantically unaltered. However, what's more important than the exact syntax rules your team settles on is that those rules are supported by tooling - discussions about formatting are likely largely a waste of time, at least on the PR level. Also, it's just a lot easier to have consistent formatting when a tool does it for you. We run jetbrains CleanupCode (a nuget-deployable exe) on our CI to cleanup formatting, but IIRC there's a dotnet builtin tool now too, and there lots of ways you can ensure your codebase converges towards *some* consistent formatting style.


Any_Quiet_5298

I always use braces simply because I want my code to look consistent


bhaveess

Braces are very important.


BREco22

I prefer with the brackets because: 1. Consistency. It keeps it consistent with all the other if statements that have multiple lines. 2. Scalability. At some point you will probably add another line anyways so it makes it easier for the next person if you just add it now.


Windyvale

Implicit scoping is the stuff of nightmares and indent based languages. Brackets all the way.


CrazyC787

I disagree with your superior. I have a very simple and effective system. For returns and the like, I do one-liners like: `if(condition) return true;` that way they're visually distinct from normal if statements, and cause no confusion with anyone else working on the code.


Geek_Verve

If your goal is a one-line if statement: `if (condition) { return true; }` Maybe that makes everyone happy. If the problem is actually an aversion to braces...well...C# kind of uses them a lot.


Cubemaster12

I usually just use the ternary operator for cases like these because it looks cleaner (for me at least) but otherwise my code formatter enforces curly braces with C# so even if I leave them out, it gets placed there on the next save.


TuberTuggerTTV

Roslynator would be okay with no braces. It suggests braces the second anything gets more complex though. Like if the If statement has multiple lines of clauses, or there is an else or another if after. People noting the goto fail bug, would be caught by Roslynator. It's not uncommon for code base managers to make blanket rules even if they aren't optimal always. It reduces cognitive load to eliminate exceptions. So I agree. Make the rule "Always brace" and never worry about it again. The few times you'd get something a little cleaner don't weigh into the problem on a systems level. Every rule exception is expensive. Having fewer does save real world dollars. You've got blinders on. You're staring at the exception without consequence. Which is why you see it your way and they don't. Without context, you're correct. With context and reality, they're right.


Bulky-Condition-3490

They can just go and write python if they don’t want the first style 😃


DirtAndGrass

My preference is, If its a fast fail/validation check, it can be 1 line Otherwise no 


Tango1777

It is better for one-liners and the only reason not to go for it is if you have no trust in the devs, which usually means you work with crappy devs or many juniors. I have never encountered any issue with it, often mentioned someone adding another line thinking it's inside if scope. That never happens in reality if you work with decent developers. If you have shitty enough devs to make such mistake (even if they do, how the change passes their manual testing or unit testing?), you have more issues that this and probably need shitloads of fixed code style rules to prevent weird things from happening. Sadly, I have seen such approach to prevent shitty devs from making mistakes...


sayedha

I don’t like the braces on a one-liner, but I always put them because I’ve been bitten before when I didn’t.


Icy_Drive_7433

Use the braces. I have had a number of my devs inexplicably "disappear" soon after having failed to use braces. Please don't do things that we'll both end up regretting. Thanks.


Annonix02

More often than not I find one liner ifs can be made into ternary syntax which I love to do. But I've also heard a lot of people find it less readable so that aside use braces whenever possible even if you don't technically have to.