The Right Way to Write if Statements in C#

  Рет қаралды 48,100

Nick Chapsas

Nick Chapsas

25 күн бұрын

Until the 30th of April, use code BIRTHDAY40 for 40% off any course, BIRTHDAY20 for 20% off any bundle and BIRTHDAY15 for 15% off your first year of Dometrain Pro: bit.ly/4aUVR8l
Become a Patreon and get special perks: / nickchapsas
Hello, everybody, I'm Nick, and in this video I want to talk about if statements in C# and which version of if statements .NET developers should be using.
Workshops: bit.ly/nickworkshops
Don't forget to comment, like and subscribe :)
Social Media:
Follow me on GitHub: github.com/Elfocrash
Follow me on Twitter: / nickchapsas
Connect on LinkedIn: / nick-chapsas
Keep coding merch: keepcoding.shop
#csharp #dotnet

Пікірлер: 699
@gianvitodifilippo
@gianvitodifilippo 24 күн бұрын
I use option #1 for branching instructions only and #4 for all other cases. Option #1 in combination with the "return early" approach looks very clean to me.
@kvurit
@kvurit 24 күн бұрын
Yeah, I agree on that, if it alters control flow such as return, break, continue or throw i think number 1 is pretty clean. Especially if you have a lot of guard clauses.
@TuxCommander
@TuxCommander 24 күн бұрын
Exactly, same page
@paulkoopmans4620
@paulkoopmans4620 24 күн бұрын
YES!
@TennysonHull
@TennysonHull 24 күн бұрын
I think form #2 is supereor for these since I think it's a happy middle ground: it's still very concise but is generally more readable, particularly for junior devs who don't know code blocks are only required where scope and multiple statements are used. Maybe I'm wrong, but I feel like the indentation makes it a little more clear whats going on for someone who isn't familiar. Edit: I was confusing #1 and #2. #1 seems like the ideal option for these use cases.
@gianvitodifilippo
@gianvitodifilippo 24 күн бұрын
Let me clarify and elaborate my comment: I avoid braces AND do indent the branching statement (return, continue, break, throw). The reason is that, in my opinion, when you have many of these constructs in a row, and you surround the statement with braces, all the extra lines slightly draw attention away from what follows those early return statements, which should be the main part of your method/block. Even if I don't have many of them consecutively, I use this style for consistency, so that this visual pattern helps me understand the control flow at a glance. Of course, this is just my own preference 😄
@TheCzemike
@TheCzemike 24 күн бұрын
I can't stop laughing -- this has to be the C# equivalent of "tabs vs. spaces"!!! I personally like terse code (everything on one line, no curly braces) but pretty much every shop I've been in requires "proper Visual Studio syntax for C# with the opening brace on its own line by itself." As long as I'm getting paid it's not worth arguing about (I'll save the arguments for bad architecture and anti-pattern uses).
@xybersurfer
@xybersurfer 23 күн бұрын
exactly. that's where the real problems are
@cgeorgescu72
@cgeorgescu72 23 күн бұрын
@@xybersurfer Yeah, but amateurs don't really understand much code so can't have opinions on the code itself, so they fight over code style. I propose fighting over the font used to write C#. What, don't you think the readability of the font is important? /s
@nicholaspreston9586
@nicholaspreston9586 22 күн бұрын
​@@cgeorgescu72 Yes, font is really nice to have, on top of general readability. I think fira code is my fav, because it's so fancy!
@adassko6091
@adassko6091 22 күн бұрын
Are you still laughing?
@cdoubleplusgood
@cdoubleplusgood 24 күн бұрын
Overarching rule is: Don't make me think. That's why we should not make a distinction between one liners and multi-liners, but always use braces. I personally don't like the "asymmetry" of #3. But if that is the standard in the project, it's fine. Curiously, C# seems to be the only from the "big" languages that prefers #4 over #3.
@marino3034
@marino3034 23 күн бұрын
"Dont make me think" is pretty subjective, hence not appropriate for a rule.
@elpe21
@elpe21 23 күн бұрын
dont like the fact that if () return 0; is being expanded into 4 lines.. Few checks and you have to scroll code :)
@thedave1771
@thedave1771 22 күн бұрын
Oddly I like without braces to reduce thinking, because when I’m scrolling around extra white space means I need to dig through more lines, I can’t see as much at-a-glance. Next line with an intend is quick for my brain. Maybe that’s just me. But always follow the local policy. CB
@smathlax
@smathlax 24 күн бұрын
I personally prefer to have if statements without the braces if the body is only one line. I don't think there is any ambiguity about the scope because you only have to look one line up to see what's going on, and if I press enter after the body, Visual Studio will automatically go back one tab so again it is clear that we're not in the if statement anymore. I think this approach is especially neat when you've got lots of if-returns in a row. It's concise and easy to read. Adding braces doubles the number of lines and it just feels like bloat. I do totally agree though that this is not a big deal and you should just do whatever your team is doing.
@luc9volts
@luc9volts 24 күн бұрын
👍👍
@Stanbeard
@Stanbeard 24 күн бұрын
Fully agree. Nick's argument here is "if you do a dumb thing it looks dumb", but the code formatter will fix that.
@user-dy8dl6xu5w
@user-dy8dl6xu5w 24 күн бұрын
Dont forget that each line in tfs (or github idk) keep link to changeset(commit). Easy to read? maybe. Easy to find out who write or override condition and why 5-10 years ago? I dont think so.
@JamieTwells
@JamieTwells 24 күн бұрын
Yes. I liked how Nick went to show us how it can be a problem, then had to fight the editor twice to get it to look confusing. It's a made up problem. I work on a large codebase currently that doesn't enforce braces for single lines and we have no issues with it.
@smathlax
@smathlax 24 күн бұрын
​@JamieTwells Haha I didn't even notice the editor fighting 😂
@AkariTheImmortal
@AkariTheImmortal 24 күн бұрын
for a single return, I use the version with the new line, but no curly braces. For other cases, I use the curly braces at a new line. I don't like the opening on the same line, but that's just a preference.
@billy65bob
@billy65bob 24 күн бұрын
Only time I include brackets for short single statements, are when I'm dealing with an if-else or an if-else chain and at least one of the levels requires brackets. In that case, they all get them for some consistency and clarity. I personally see no reason to split guard clauses over 4 lines, where a short one-liner will suffice.
@betterlifeexe4378
@betterlifeexe4378 24 күн бұрын
I like one line no brackets if (an only if) it actually fits on one line. Nothing can be easier to digest, its basically a plain English sentence. Everything else gets brackets and it's own line.
@StarfoxHUN
@StarfoxHUN 24 күн бұрын
Its sounds fun up until for any reason you have to add an extra line and now you have to add those braceles. And it happens ways too often to justify at least based on my experiences
@WarrenGarabrandt
@WarrenGarabrandt 24 күн бұрын
That's ok. It's ok to be wrong. :D
@LilPozzer
@LilPozzer 24 күн бұрын
​@@StarfoxHUNoh no way, adding two more brackets, what a waste of time 😢😢
@betterlifeexe4378
@betterlifeexe4378 24 күн бұрын
@@StarfoxHUN if (condition) return; single conditional guard clauses is mostly safe from this. Also, there can be very clear preconditions for if (condition) ExternalMethod(); that are safe.
@joshpatton757
@joshpatton757 24 күн бұрын
@@betterlifeexe4378 I personally only allow one-line for guardian clauses - I don't even allow it for a method call. If it's not at the stop of the function and i doesn't return, then it should be multi-line. (In addition to being short enough, single conditional, simple return statement).
@sasukesarutobi3862
@sasukesarutobi3862 24 күн бұрын
With the third point in the post ("Anticipates the need for adding more logic without rewriting existing structures"), I think they're referring to the fact that if the structure is already one that supports multiple lines in the inner logic, then the structure won't need to be changed if more lines are required in future changes. Changes that do need to add braces that turn up on git diffs (and add noise to a code review) are a bugbear for some, so always having the braces means future expansions will only diff the new lines and not some structural changes that don't actually impact function.
@TheNeozas
@TheNeozas 24 күн бұрын
@@IIARROWS you are looking from the position of good IDE or merging tools. But some strange people still use default VS Code or worse to do their job and they think a bit retrograde. And big problem that they are usually very "experienced" and have their positions of power
@xybersurfer
@xybersurfer 23 күн бұрын
@@TheNeozas good point. not that it justifies them using crappy IDEs
@sasukesarutobi3862
@sasukesarutobi3862 23 күн бұрын
@@IIARROWS I absolutely agree, but I just know that it frustrates some people if they're having to sift through lines to find changes that actually have an effect on the code. It tilts their signal vs noise ratio.
@ApacheGamingUK
@ApacheGamingUK 24 күн бұрын
For early returns, continues, breaks, etc., I like single line, no fuss, no added real estate. "if (array is null) continue;". I don't want a separate code scope purely just to return early. I will often separate the condition from the if statement, to keep the early return small. It helps the code read better to put a hard break on early returns, continues, breaks, guard clauses. These are things that should never need extending, or debugging. They are the debug markers. If x is bad, get me out of here. Fail first, fail fast.
@Fajerkoks
@Fajerkoks 24 күн бұрын
I generally use brackets on a new line, but in situations where I need to break a method using return, I do it without brackets in the same line as the if statement.
@THPieta
@THPieta 18 күн бұрын
I personally lean towards the 3rd style because it's clear and space-efficient (especially vertically), making it ideal for presentations where every bit of screen real estate counts. It neatly marks the start and end of a block, which really helps in keeping code both approachable and compact.
@jongeduard
@jongeduard 24 күн бұрын
I have ALWAYS used braces in my if statements, to avoid the mentioned bugs. Which bugs which can even have security implementations (code that shouldn't run actually always runs due to improperly written conditional statements). With the `using` statement I generally base this choice on whether or not the place in my code where Dispose is going to be executed actually matters. This aware approach reduces overloads of indentation levels in my code in a lot of cases. But I understand when people choose to not use the short version at all. When it comes to braces positioning. These days I use whatever is conventional in the language, just like naming conventions. In C# this is the Allman style. When writing C code I also use this style. Not when writing Rust, Java or JS where having the opening brace is on the same line as the header is conventional. But still my preference in general is really this Allman style, because seeing both braces in the same column is still the most readable to me. Seeing only closing braces on the start of every line is simply a disadvantage. And additionally, the argument of reducing lines with the other style is of limited validity. In many cases people still type an extra whitespace, especially in Java, to make code more readable, so that in the end this advantage is gone. Why not just put the brace there if you already want that extra distance?
@wesplybon9510
@wesplybon9510 24 күн бұрын
It's kinda context dependent TBH. - If I'm doing early out checks, (i.e. input validation) then I might do a single line to keep things compact, as long as the return type is simple/scalar. - If the conditional clause ends up quite long, I might bump the return down to the next line without brackets - If the above situations involve complex object instantiation, then it will end up multiline with brackets. - If I need an else, there will ALWAYS be brackets around both sides (...what kind of monster leaves brackets off of only clause of an if statement??) - Opening bracket ALWAYS goes on a new line to keep brackets lined up. This might horrify some of you, but I don't have a single set rule. Optional markers (like some parens around arithmetic operations) can be added to provide clarity and readability. If a question of readability pops into my head, though, I won't debate with myself I'll just go with the more explicit layout.
@DanGolick
@DanGolick 24 күн бұрын
The compiler will understand all of these without a problem. Coding standards are to make the code easier to understand and modify. The reason I think we must use braces is because so many new programmers start with Python, where indentation implies scope. They will easily make mistakes in modifying no brace if statements. Placement of the opening brace is purely a style issue, and different shops will use different standards. Ideally you run a pretty formatter with your shop's rules before check-in. There is nothing worse than someone checking in code with a bunch of changes with both code changes and global format changes. In this case to see what changed you must visit each white-space change and check that it does not create any code change. If you decide to change the overall format do a formatting only check-in, so that others don't have to review a bunch of format changes. Ideally the IDE would let you view the code in your preferred format without changing the code.
@AnatoliiMakarov
@AnatoliiMakarov 23 күн бұрын
I agree with what you said “one thing at a time”. In addition to being a common C# code convention, it also allows to quickly comment out a condition or a body with a one-line comment to change the behavior during, debugging, for example. In case of commenting on if line, this does not require replacing with/or adding “true” to the condition; When commenting on a body line, it allows to skip the entire condition. Both of these cases cannot be applied to all other options without changing the code.
@berry212
@berry212 24 күн бұрын
Return success?
@andreyz3133
@andreyz3133 24 күн бұрын
what if there is more than one condition?
@m057d0p3
@m057d0p3 24 күн бұрын
@@andreyz3133 ad switch ;)
@WilliamLeeSims
@WilliamLeeSims 24 күн бұрын
:) I thought the same at first, but it's not quite the same... in Nick's example, if success is false then more code might execute underneath.
@mirabilis
@mirabilis 24 күн бұрын
if (!success ^ true != false) { return success ? true : true; }
@tcortega
@tcortega 24 күн бұрын
He is talking about the coding style, the code demonstrated is indeed redundant but you don’t have to be a smart ass about it :D
@emloq
@emloq 24 күн бұрын
It depends every case, if the condition and the statement are short enough, I'll use 2; If one of the two are too long and can be confusing, I'll use 1; however, if in some way, the code above or below the if is blob-like and the if could be ignored by mistake, I'll use 4. I only use 3 in TS and not C# bc I use the default braces setting in C# but by preference this is my tier list: 2 > 1 > 3 > 4
@JoshOlsonDev
@JoshOlsonDev 23 күн бұрын
Older arguments about how you should format something for future maintainability are certainly valid. For minimal source control diffs, also valid. However, source code is read much more than it's diff'd, so compactness is much more valuable to me. Why read all these whitespace and syntax tokens when it doesn't change anything? Anyone moderately seasoned in reading code can grok a half screen of code at a time to find where something should be modified. If you're adding brackets above and below the meat of everything you do, you're making it so you have to scroll 3x as much to look at a (probably) ridiculously simple (in context) piece of code. That's a waste of time. Oh, you're concerned about not being able to read a stack trace and immediately know what the issue is? Have you considered writing more E2E tests so you look at fewer stack traces? This whole argument boils down to where you want to spend your time. I value reading code quickly so I want my team's code as compact as possible. I will use formatting tools to add or remove braces, add or remove new lines on save. I will save as frequently as possible to be as lazy as possible. All the fabricated examples in this video are exactly that -- if you have auto-formatters in your project, you will very quickly notice when you save that the 2nd line in your un-curly-braced statement gets unintended and you did something wrong. Also, have I mentioned you could just have tests to catch this mistake?
@modernkennnern
@modernkennnern 24 күн бұрын
I'm consistent. Blocks - no matter the size - are always surrounded by curlies, and curlies in C# are always on their own line.
@paulomfgoncalves
@paulomfgoncalves 24 күн бұрын
C# is not java !!!
@AnsisPlepis
@AnsisPlepis 24 күн бұрын
I also like to stick to this rule for consistency and I find that giving control flow statements space makes them easier to read. At first I heavily despised this convention but it’s grown on me
@TazG2000
@TazG2000 23 күн бұрын
Using braces regardless of the number of lines in a block increases consistency, but adding new lines before opening braces does not. In fact, consistency is the reason I choose NOT to use the extra newline, because from a multi-language perspective, Microsoft's C# style is inconsistent. Among other languages that use braces for blocks, the most common formatting is with the opening brace on the same line.
@paulomfgoncalves
@paulomfgoncalves 23 күн бұрын
@@TazG2000 iis not true!!! using the opening brace on the same line in C# proves to be a bad programmer or an unsuitable non-compliance... but in Java it is correct. Another example: in C# method names start with a capital letter and in Java they start with lowercase letters... Not respecting rules in a work group is always bad!!!
@TazG2000
@TazG2000 23 күн бұрын
@@paulomfgoncalves So are you under the impression that every work group using C# uses the same style? And only uses C#?
@brianviktor8212
@brianviktor8212 23 күн бұрын
In general the multi-line approach (including with usings), of course { on its own line because it looks more readable - you see the structure better. When it's simple, single line. If the return is just a boolean (or "return null"), it doesn't need braces. If the if statement is more complex, but the return is a boolean, here's a tip: "return x > 5;" instead of "if (x > 5) return true; else return false;". If it improves readability I may resort to multi-line. If it's a more sophisticated if-clause, I just use braces. Prime examples are "TryGetValue"s from dictionaries. When I have initial checks at the beginning of methods like "if (count < 0) return null;" I always add an empty line below to indicate that it's a potential method-ender. It is the style I developed on my own, and it's a mix of mostly having a consistent style and sometimes a judgement call. I believe however it's possibly one of the most well readable styles that exist. If I knew about improvements, I'd probably just add them. Which I btw did a lot.
@laurentallenguerard
@laurentallenguerard 24 күн бұрын
I agree with you, it's way simpler to read if there is one element by line. Also, I add spaces after and before parenthesis to make more contrast in my eye to read the words. Spacing code make less code visible in the screen, but you can understand it and spot errors faster. Then my coworker comes in with it's auto indent and the beautiful code I left is destroyed into a grid of unintelligible characters. This is brutal. I do beg him positively not to destroy my indentation, it keeps happening again. You can always use empty line shrink if it really bothers you. Ahhh juniors; hopefully one day he will understand.
@WilliamLeeSims
@WilliamLeeSims 24 күн бұрын
I put curly braces (on their own lines) for everything; it helps readability and future maintenance. I've recently made one exception: I put the first curly brace of a lambda expression on the previous line. It's a visual note to myself saying "hey, this code isn't going to execute in an imperative way".
@JohnPeter-yf5jf
@JohnPeter-yf5jf 24 күн бұрын
@@IIARROWSthe only single line is simple returns on bull checks at the start of a method. If you have multiple ifs you’re either doing it right, or it should be broke up only you know the use case.
@joshpatton757
@joshpatton757 24 күн бұрын
@@IIARROWS Hiding braces on lines with code is far less readable than a few extra lines, IMO. I want to be able to quickly visually scan the code and see the high level structure, not have to pause and hunt for curley braces. Spinning the scroll wheel for a few extra lines is still much faster.
@evancombs5159
@evancombs5159 24 күн бұрын
I do this with lambda expressions too. I think developers often don't understand that every space, curly brace, and indentation is communicating something. My background is more in design before I came over to programming, this is why I do not agree with those who say readability is subjective. Those people do not see the design in their coding practices, and therefore do not understand how that design affects how their code is communicating itself. There are certainly things that can go either way where you are debating between two equally good or bad options, but most of the time there is an objective best option. You just have to stop looking at your code like a computer, and start looking at it like a designer.
@demarcorr
@demarcorr 24 күн бұрын
i run a custom formatter over my code to randomly style my if statements in all ways shown. jokes aside i use MS convention unless im doing very simple guard clauses, in which case ill use single line. I collab with friends and my coworkers who vary but this isnt an issue for us because uh we're grown adults and have better things to expend calories on.
@DoubleBullet
@DoubleBullet 24 күн бұрын
Aww but I want to be the center of attention for online arguments and belittle other peoples opinions for it even though I might be new to programming and the person being harassed by me is a 30 year senior software engineer. You’re one of those “peacemakers” aren’t you? Ironic much? 🧌
@demarcorr
@demarcorr 23 күн бұрын
@@DoubleBullet ...... what?
@DoubleBullet
@DoubleBullet 23 күн бұрын
@@demarcorr sorry
@codingbloke
@codingbloke 24 күн бұрын
Way to open the floodgates Nick! From my point of view I prefer the MS standard of opening brace on a new line. My reason for this preference are twofold. First I like the that little bit of white space which I think adds clarity to the code and that the I can eyeball the alignment of { with }. However, a key reason to stick with this approach is to help context switching between languages. When devs are working full stack they work both with Javascript and C#. I have seen primarily javascript coders do some server side side work and get confused. There some things that syntactically will compile but not quite do the same thing in C# that is does in Javascript. The placement of { can be helpful, almost subconscious, clue which language we are working in. I completely agree that a multi-line if without { } is not desirable. A modern IDE will tend to format the code to clue you in if you are making a mistake but we shouldn't rely on that. However I'm completely fine with a single line if (no braces), when used a) as a guard clause right at the top of method (an early return, or throwing an exception), or b) whose body is a very simple assignment. Sometime 1 line instead of 4 is just cleaner.
@markmundy9582
@markmundy9582 23 күн бұрын
Had an interview years ago with a guy who worked with Brian Kernighan (of Kernighan and Ritchie fame). Someone asked why they did all of the examples in the book C Programming Language with the open curly brackets on the same line as the statement, and is that what they preferred. Kernighan replied they did it that way solely because their parser could only read one line at a time. But, at that time, he truly preferred the open curly on the next line. That's as close to gospel as I need
@antonzhernosek5552
@antonzhernosek5552 24 күн бұрын
Single statement with a very simple return value (like a bool, or returning null) -> can be on the same line. Concise statement with a non-simple return value -> new line. However, I've lately started using newline as a default even for simple returns, just to be more consistent about everything. Everything else -> braces. How they look doesn't matter much, but I'm used to working with the MS standard. IMO it reads better when you clearly see where the code block starts and where it ends. Otherwise when I see a closing brace, I have to go up and look for a statement that is on the same indent level (which can be "class", "if", "switch", "using" or something else). The alternative is that I look for an opening curly brace, which is more consistent for my brain to adapt to
@yetanotherdex
@yetanotherdex 24 күн бұрын
Always use curlies, and put the opening one below the iinitial statement. Do this where ever you 'could' remove the curlies (all statements where they are optional). - This gives a 'stable' code style, meaning, every if looks similar in style (not some with and some without), is a maintainability factor as it becomes easier and faster to understand the code. - Another maintainability factor is how easy it is to actually change the body of the statement (e.g. add a line), as it is always the same, and there is no need to go out of your way in order to add the curlies if you need more. - Not putting the statement at the end of the same line keeps the line short, which supports vertical reading, which also improves maintainability as the code becomes easyer to consume and understand. - Putting the opening curlie to the front also supports vertical reading and thus is good for the same reason. - The curlies also give a visual boundary which always helps to identify blocks, making it easier / quicker to understand. So the main reason is maintainability (you may not see a reason for that yourself, but other people who have to read your code at a later time will understand). Thx for reading to the end. Now ignore everything i said and post your own opinion ;)
@aldelaro
@aldelaro 24 күн бұрын
This is something I have lots of strong opinions about because I really hate the version where the brace is on the if's line. The reasoning is because I have to visually look around more to see the correct bracing. This might be minor, but for me, it's a bigger problem because I am visually impaired: I have to zoom in on my IDE a lot and I STILL need to move my eyes more than usual. Having the brace directly under the if makes it way easier for me to tell what scope the if is in. It especially makes it better for nesting or when the if happens to be a long line. However, I also think single statement ifs get annoying because if there happens to be a lot of them close to one another, the braces adds a lot of noises. Due to this (also inspiring from a convention from an oss project I contributed to before), I made up a middleground: - If any of the branch of an if chain requires multiple lines or if making them take more than one line improves readability, ALL branches must have braces - If none of the branches needs multiple lines, all have no braces, but have the code a line below indented This only applies for a given level of nesting. I think it's the best middleground between noise reduction and being visually faster to check what's happening. I never use the second one where there's no newlines because it's a bit too much and it actually makes the problem worse visually than having the brace at the end (unless it's like a switch expression or something). As for the scoping issue if you don't use brace, I get into the habit of having a blank line before. The reality is that this pattern is too common if I think of method's early returns for me to not try to minimise the noises of the braces if I can.
@orionsteel5921
@orionsteel5921 23 күн бұрын
Interesting. You are actually the first person who gave me a reason for wanting if ... { ... } That didn't simplify to "I just like it better" You have a valid and objective reason for why it is better. Thanks for sharing.
@zbaktube
@zbaktube 23 күн бұрын
third: using var -> I got used to it with Go. But I used to do it as you for the same reason. I just realised how Go changed my C# style, funny
@CuriouslyContent
@CuriouslyContent 24 күн бұрын
I use option #4 always for 2 reasons: 1) aesthetics, I like the spacing, I like the symmetry of the curly braces and that #4 has identical look/structure to all other 'if' statements. This means there is zero mental overhead to parse what you are looking at. For me, as soon as the visual structure of something changes, my brain has to start working to ensure I am looking at what I think I'm looking at. With #4, I see the 'if' and 2 curlys and I know there is no trickery afoot. 2) if I need to add more code to the condition, I (or junior dev) don't have to remember to add braces. So a bit of laziness (since the initial curlys are automatically added by my IDE) and a bit of defensive coding.
@DemoBytom
@DemoBytom 24 күн бұрын
I use the last one, the C# convention, backed up with an .editorconfig and dotnet format ran on commits and during the build process. I also have Visual Studio set up so it adds the braces and/or newlines according to the convention set in the .editorconfig. That way I don't have to think about it while writing, my IDE fixes/refactores the code to stay consistent across the project(s).
@perdonomai8060
@perdonomai8060 24 күн бұрын
1. Always use open bracket in new line with multiple statements 2. return success; for one liner (return ) 3. or no brackets for single line (two lines for open/close brackets are t0o many "useless" lines) if x = y
@Deathflame82
@Deathflame82 22 күн бұрын
Steve McConnell spoke about this in deep in Code Complete. I suggest everyone to read that part to clarify the ideas, and see that some alternative are not about preferences. The braces vs no-braces option is a matter of scope and preventing misleading additions. Where to put the brace is a matter of code blocks. C# in general puts the curly braces on a new line (ie for classes) but on the same line for method invocations. An open brace is not the same as a close brace. The open one is part of the declaration, it can be at the end of the line so you have a 3 blocks; Declaration +open Body Close bracket Instead of 4 Declaration Open Body Close The Open does not add anything relevant. Of course it must exist but visually and for your mental model it does not do so much. While the Close is mandatory also for your mental model, to close the scope. So I think the curly at the end is better (like Java) not only for if statements but for all blocks, but C# puts on a new line so let's follow the convention.
@rainbowsprinklez
@rainbowsprinklez 24 күн бұрын
I used the opening bracket on the same line with JavaScript. I've been coding for years in C#. Now I switched to your latter example. Thank you, Microsoft, for force feeding me this method :)
@TennysonHull
@TennysonHull 24 күн бұрын
Used along with other sensible formatting practices, I would argue that single-line statements (without brackets) are more readable and have their place in naturally concise control statements. Option #1 is highly readable and particularly useful when it comes to things like simple guard clauses. Obviously this is just my personal preference, which will always be overridden by practices/standards/guidelines for the project I'm working on.
@Moosa_Says
@Moosa_Says 23 күн бұрын
I prefer using 2 { } on their own line. i think it's just more structured and easy to understand. Yes, even better than the first !
@GirlAteDeath
@GirlAteDeath 24 күн бұрын
10 years experience, not once i saw an error with wrong indentation. It’s literally impossible with modern ide. Maybe in other languages but not in c#
@sacalbal
@sacalbal 24 күн бұрын
I encountered 2-3 in very old program. But previous developers on this project were either really bad or newbies. Maybe the IDE is better now, but I still find the "no curly braces" version confusing.
@slipoch6635
@slipoch6635 23 күн бұрын
I have a rule, always use curly braces. The amount of legacy code (over 6 separate legacy projects) I have seen with bugs due to not including them where someone has made an update later and part of the statement drops out, then it isn't caught for years. Pretty much this plus continues inside large amounts of code were responsible for ~80% of all bugs. if it is a single line I may do it all on one line with curlys, or for personal use in multi-line situations, the opening curly will be on the opening line (after the if statement) and the closing will be at the end of the last line, not on it's own line. Took a bit to get used to, but it works well. One of the arguments against braces I simply do not understand was "We don't want people trying to find the end braces", which I honestly had no reply for as I couldn't see how that could be an issue for a programmer.
@ErazerPT
@ErazerPT 24 күн бұрын
The preferred style of MS, which is also mine, is Allman style. There's a video by Kevlin Henney somewhere which goes to some length about it, but the fundamental part is you eyes/brain can track "rectangular blocks" with extreme ease, so intuitively you know what is where and what scope it's in. People with some design background grep this instinctively. The usual "Javascript style" is K&R style, which is not awful, but we track paralelograms far worse than rectangles. It was VERY relevant when The C Programming Language was written as vertical real estate was at a premium, but seriously, nowadays... And if you can afford it, having a 2nd (and sometimes 3rd)monitor life changing in QoL terms. Add some rotating arms and it's heaven.
@renynzea
@renynzea 23 күн бұрын
I use whichever of the 4 most closely matches the code style around it. For new code I'll use the single line version for short circuits or to split apart complex or statements or unary operators into a chain of simpler statements I can read. If I am returning a value of any significance I'll use the multi-line return with braces on their own line. Basically, whatever makes the code easier to read. I generally don't care much about style as long as I can read it. The only thing I'll harp on is not multi-lining fluent method chains, or breaking apart complex boolean evaluations with nested groups into a more obvious multi-line nested structure.
@1992jamo
@1992jamo 24 күн бұрын
I don't use braces if I don't have to. It makes the code more concise and readable to me. Having said that, if it's not a single statement and I have to use braces, I use them on a new line. It helps me keep track of scopes.
@pilotboba
@pilotboba 24 күн бұрын
The problem with this is, it really common to add another statement you want to run if true without thinking you need to also add the braces and break code, sometimes in subtle ways that might be hard to track down.
@1992jamo
@1992jamo 24 күн бұрын
@@pilotboba I can't understand how this happens if you're vigilant with indentation
@pilotboba
@pilotboba 24 күн бұрын
@@1992jamo I've seen it happen. It's easy to be in a hurry, be tired, etc. Also juniors may not even know that semantic, or come from a language when white space and indentations define the block, etc.
@TehKarmalizer
@TehKarmalizer 22 күн бұрын
You can’t account for people simply not understanding the language. I also think the argument that you might want to add more statements later is weak. It does add a little more to a diff if you commit or take slightly more work to add debugging statements, but otherwise it’s pretty concise. I usually just use the braces anyway, but I don’t really think about it overmuch.
@pilotboba
@pilotboba 20 күн бұрын
@@TehKarmalizer I always design and architect for people to fall into the pit of success. For the same reason, I instantiate all lists to prevent the need for null checking lists.
@JamieTwells
@JamieTwells 24 күн бұрын
My preference is #1 I try to keep all conditions/loops one line long so its consistent that the { } aren't needed. On personal projects anyway.
@klocugh12
@klocugh12 24 күн бұрын
Same. Indentation for readability and VS autoinserts it on Enter anyways.
@nishudar
@nishudar 24 күн бұрын
Totally agree, and this whole discussion is pointless
@HollandHiking
@HollandHiking 18 күн бұрын
I always use the fourth. For me it looks better and the advantage is that the brackets are aligned, which makes it easier to match them. For the simple example, it doesn't matter that much but for more complex code, I appreciate that a lot.
@WarrenGarabrandt
@WarrenGarabrandt 24 күн бұрын
Always 4 if it's my code. The { and } on new lines very clearly delineates a block that is much more noticeable than tacking a { onto the end of a line. That's important for me when scanning through a file because I look at the left side of text and track the { and } to mark blocks of functionality in my head as I go. and it helps me to identify nesting mistakes much more quickly. I will give 3 a pass if it's in a source file that I didn't write, or if the style guidelines for the project call for it, but I won't be happy about it. 1 is unacceptable, and 2 is an unforgiveable transgression that must be fixed before I will continue work on the project. And goodness that first using statement example was cursed. I thought the only way to properly construct a using statement was with the parameters in parenthesis and a braces delineated code block after it. Otherwise, how does the compiler know when it's supposed to be out of scope? I can't imagine that Anders Hejlsberg would be ok with somebody butchering his language by leaving code block braces out of a using statement.
@sebiederer
@sebiederer 24 күн бұрын
I am always using braces and you already explained the reasons in the video. And honestly, I don't care if I put the first brace in the same line as the if-statement or not. I try to adhere to the conventions of the language, because people using a specific language are more likely to know these conventions, but I am not very strict about that. E.g. I am putting the braces in extra lines in C# and in JavaScript I put the brace in the same line as the if-statement. I do that because people used to different conventions depending on the language they're using. However, what I am strict about is consistency, but that's what auto-formatters were made for.
@petedavis7970
@petedavis7970 15 күн бұрын
Before auto-indenting got good, it was part of our code guidelines that you always used braces. The reasoning being that if you neglected to and then added additional code afterwards, you might forget (and people did) to add them and your code wouldn't work as expected. These days, with auto-indenting, that's not really as much of an issue. But what I have noticed is that that code is also more readable. I continue to use braces for single lines, but I'm also a consultant and so I usually adopt the styles of my clients, even if it's not my preference (unless I can convince them to change).
@MorcamOne
@MorcamOne 24 күн бұрын
One of the default plugins with Productivity Power Tools in Visual Studio is actually Shrink Empty Lines, which slightly reduces the line height of lines that only have a curly brace on them. Makes #4 look pretty nice.
@vertxxyz
@vertxxyz 24 күн бұрын
Seems weird to state that debugging with collapsed lines isn't an issue if you're using a good IDE, but to ignore that any good IDE would tell you if indenting was confused in relation to the scope. I personally use the braceless version on multiple lines, and sometimes collapse it to one line each for tight loops with multiple simple continue statements. Braces on new lines when using them.
@darkwater234
@darkwater234 24 күн бұрын
Topics like this are fun to discuss, but at the end of the day, you need to be able to read just about anything. It is a nice idea to leave well-formatted code with good naming for the next dev. At the same time, you need to be ready to read code in any state and make sense of it.
@colindawson4818
@colindawson4818 24 күн бұрын
From your 4 examples. I'll use 1, then switch to 4 if there's more than single action in the block. In addition if there's an else block, I'll be more likely to use the braces regardless, to save brainpower when coming back to the code. This is for c# code. For Javascript/Typescript, I'll use 1 & 3 pretty much everywhere for the same reasons. Whilst it may sound like a very small thing, it does help to keep my brain thinking C# for the C# code and JS for the JS Code, there are plenty of other nuances to the languages, so having a tiny detail like that will help to keep the amount of brainpower needed lower when switching between different languages. This doesn't make other peoples choices wrong, and I won't flip out if I see the other way of doing it, it'll just make me think more and ultimately slow my progress.
@DimasMessias-kl4ic
@DimasMessias-kl4ic 24 күн бұрын
My current project uses the C# approach for Java code. It was a code written many years ago and keep the standard. I even made Intellij format it that by default for the specific project. When it comes to newer code, the Java standard is applied, the same goes for C# Using braces helps during resolving code conflicts, it was useful is different situations.
@dde-fz7ih
@dde-fz7ih 17 күн бұрын
When I was a 30 years old developer I would have chosen Option #4, for the same reasons you explain in this video. Now that I am a 50 years old developer, I tend to choose option #2, if the statement inside is trivial and short for readability which is IMHO the most important criteria. If the statement is a bit complicated or long, I go for option #4, again for readability. I let you choose if it's selinity or wisdom :).
@HarleyPebley
@HarleyPebley 23 күн бұрын
Ugh. Tempest in a teapot. In order, my personal preference is multi-line/no braces, single-line/no braces, multi-line/braces at same level and multi-line/braces at different levels. But I've been around long enough to know this isn't a hill to die on. It's simply preference. And I'm not even concerned about consistency in a project. I know: that's heretical to some. Meh. I'm more concerned about architecture issues than syntax. I read somewhere quite some time ago, and I wish I could remember where, but can't, that formatting preference tends to change depending on the length of time developing. I seem to recall (but could very well be wrong) that less experienced developers prefer less horizontal spaces and more vertical and with more experience it inverts. Or it could be vice versa. But I found it interesting that it tended to change over time. And the whole "If you're professional, you'll do it this way." Please. That's rediculous.
@CodeOptimism
@CodeOptimism 24 күн бұрын
For early returns at the top of a function, if there are many, short and obvious, I'll use `if (condition) return false;` for each. For early returns a little later, I'll use ` if (condition) return false; `. For actual conditions within the bulk of the method body, I'll generally use OTB. I frequently re-read every line of code in a sufficiently-independent module the moment I lose sight of the "whole picture", and less verticality helps. There *IS* a philosophical reason I do this, but it's a little complex to explain, having to do with diminishing returns and the square-cube law. Essentially at some point we're writing support code for our support code-an inefficient animal of extra bones merely to support its bones; I hold back the tide as long as possible. I prefer confidence in my understanding rather than programming defensively for the same reason (the less code, the less code needed). Let me hit the error so I can correct my understanding and inform my next commit. There are obviously code bases where this doesn't apply and I will always conform to existing styles: gotta PR those bugfixes, make it as easy as possible on our benevolent maintainers.
@wtflolomg
@wtflolomg 24 күн бұрын
I started coding in the 80s with Pascal, so multiline with braces (2) has been my style through C then C++ then C#. Scoping is always important, too, and the formatting with braces on their own lines, provides clarity.
@marcusmajarra
@marcusmajarra 24 күн бұрын
I tend to not use one-liners for if statements, but I might for straightforward switch case statements that map to return values. Otherwise, I tend to systematically introduce scoped blocks, with a new line before the opening brace. Like you said, it reduces cognitive load because there is no ambiguity as to what the scope applies to, and placing the opening brace on its own line allows me to more rapidly scan for the start and end of the same block since they will be aligned with one another. I often find myself looking through bad Java code where the convention is to place the opening brace on the same line as the condition and have to ask myself where a particular block started. Sure, a good IDE will provide you with this information, but I would rather not need to rely on specific IDEs to keep my code clear and consistent.
@logicalsparrow2130
@logicalsparrow2130 24 күн бұрын
if (success) return true; I use this form as long as the scope it's in has curly braces and is well-formatted. This form is helpful when all the logic in a scope has this shape (including approximate line length) so the vertically-compacted text is easier to see at a glance. If the logic around it has a variety of shapes, then I would use the 4-line form instead. if (success) return true; I avoid this one as much as possible. It's annoying for debugging. if (success) { return true; } I find this form to be less helpful than the 4-line form. When the opening curly brace is on it's own line and vertically aligned with the closing brace, it becomes much more clear when the condition and body become very large. If on your screen you see a closing brace and expect the form above, when you start scrolling you have to be prepared to stop when you find an if, else, for, while, foreach, switch, switch expression, using, method, class, or namespace. This is cognitively more difficult than simply looking for the opening curly brace directly vertically aligned above the closing one. If you use a shortcut to jump to the curly brace and the condition is very long, you can end up scrolled way to the right and this may be annoying. This is especially applicable when doing code review outside an IDE, e.g. github. A few notes: 1. Never nest the no-braces forms. The risks of issues grows exponentially. 2. Never have a no-brace form surrounding a with-braces form. E.g.: if (condition) foreach (char c in myString) { DoSomething(c); } This breaks the idea that a no-braces body is one line so it's harder to read. 3. If any body in an if-else chain has braces, they should all have braces. This is generally to be consistent to simplify cognitive processing.
@ClawGr
@ClawGr 23 күн бұрын
Same way with the getters. If the logic is small (eg. return bool) i would write it in a single line in blocks, What matters, is to write it in some consistent way, that is not distracting you about scopes etc.
@marccygnus
@marccygnus 24 күн бұрын
I've been doing both Windows and embedded engineering for more than 3 decades. A good bit of it was realtime and safety critical. I got into the habit of always putting a block after an 'if', next line for clarity, and I've never gone back.
@drndn
@drndn 23 күн бұрын
A key reason that having opening braces on their own line is the best, partly because it keeps things looking nice when the thing before the opening brace is long enough to wrap onto multiple lines; also it has better symmetry for all code sizes.
@cgeorgescu72
@cgeorgescu72 23 күн бұрын
Exactly, code looking nice, that's why I started to experiment with various fonts, I use Times New Roman in C# but for JavaScript I use Lucida Handwriting 12p, it flows better.
@MarquisKurt
@MarquisKurt 24 күн бұрын
When it comes to braces, I follow the convention for the language. Since I often write in Swift, having the opening brace on the same line as the condition is standard practice. In C#, I follow the conventions there and put the opening brace on a new line. I don't use single short statements as often since it's not allowed in Swift (you still have to wrap in braces), and the only times I would ever do it would be in C, not C#.
@alexandernava9275
@alexandernava9275 20 күн бұрын
I use one, for the simple matter that it leads the eye through the logic more. I, as many, use empty space to indicate breaks in log chunks, by using one I see the breaks in logic easier in code, as it is clear that the logic inside the conditional statement is directly attached to the statement
@asagiai4965
@asagiai4965 24 күн бұрын
I kind of prepare #4 most of the time. But here's my take on the different approaches. #1 is for single or simple logic with simple return/result. #2 is for complex or long logic with simple return/result. #3 I don't really get the point of this one. But I think it is good for formatting inner ifs.
@tellur808
@tellur808 24 күн бұрын
I prefer 1 for simple situations (early returns or small checks) when there is no risk of ambiguity. E.g. I just started a try scope and it's time to check if all my ducks are in a row: try { If (!connected) throw new Exception ("oops"); Dostuff(); } catch (Exception e) { ... } This is fine and makes a list of prerequisites more concise. I'll also omit brackets if there are several different single statement scopes in quick succession If(A) DoA(); If(B) DoB(); Else DoC(); ... If one branch of an if elseif else block needs brackets, all will get brackets. I prefer 3 when the statements and conditions are both short, but I will use 4 if either is more complex. "Big" structures like namespaces, classes and methods will always use 4. Basically 3 only gets used if the 1-2 lines extra per scope make up a significant portion of the linecount for that scope. 2 lines of statements surrounded by 2 lines of brackets is just a waste of space for no appreciable extra clarity. If there ever is a risk of ambiguity I default to 3 over 1 and 4 over 3. I use both C# and Java and work with a codebase that started with 3 and recently switched more and more to 4. Also since I often work on client-specific code that on the extreme end has been migrated trough the different versions almost unchanged from the early 2000s, style consistency is inherently spotty.
@___bf____
@___bf____ 24 күн бұрын
Vote for #1, but only when If + return. No braces reduce vertical code space, less confusion for the eye. Use two lines due to edge case where return statement is long (?:). Visually separates method entry block from method core block. Most common use case: validation logic, prevents deep nesting (return rather than nest) and enforces clear code struct by handling all "elses", therefore easier to ensure unit test code coverage. When no return, it's very easy to visually misinterpret the separation between the if follow-up and the next line in code (not part of if block), especially in C++ where a missing semicolon can actually compile into something unintended (think macros). #1 is valid for all C style syntax langs (c, c++, java, c#). #4 is too spacey, requires lots of scrolling. #2 will cause all sorts of visual congestions, used to love that one when i was 13, in Pascal 7 :). Horizontal scrolling is worse than vertical as it hides the rest of the code, thus reducing readability. All of the above are measurable facts and will have an exponential impact on coding efficiency, driver being the level of exhaustion of eyes and brain + stress levels & caffeine intake :)
@haffneralex
@haffneralex 14 күн бұрын
perfect
@sealsharp
@sealsharp 24 күн бұрын
I like my return/break/yield at the start of a line not somewhere within it. Visually looking for return/break/yield to get the flow of a method is much easier if you know they are at the start of lines and not potentially everywhere.
@donr484
@donr484 23 күн бұрын
I like starting curly brace at the end of the first line, just like I would use for parens after a function with many params that are each on their own line. It keeps things consistent, scalable, and concise. Doing it without curly braces is really tough to follow sometimes. Is the statement part of the condition? Where does one start and the other stop? It's also not scalable if you need multiple lines inside the curly braces or if you have a large expression with multiple ands/ors, etc. That forces you to have conditional formatting conventions. Using up horizontal real estate is the bane of productivity imo. Scrolling vertically is trivial with a mousewheel. I like to have as many vertical panes of code open as possible, and often split them to be able to reference different parts of the same file. If I have code overflowing horizontally or if I have to switch windows to view different files very often, it slows me down considerably. I prefer very strict outline formatting, going way further than most IDEs enforce. I will do condtions in an expression on one line each, but for variable assignment I like value on the next line indented after the equal. I also prefer to use named params, again putting values on the next line indented. When you have varying length variable names, it lines up all the values vertically and often avoids horizontal scrolling. It works in nearly every language, even html.
@nicktech2152
@nicktech2152 24 күн бұрын
I actually prefer if(success) return true; And the reasoning behind it is to actually assure the reader that there is exactly one line to be called after the if. It also imho looks nicer in short-circuits where you are doing checks early in the method and stacking up a multiple ifs. I think it is important to understand that it’s also about the amount of lines of code - some people with sight problems prefer to have a bigger font, thus less code fits into the screen, thus saving extra lines becomes more valuable than outlining the scope. But at the same time I hate having a single lined if(s)return true; However I’m writing like this when I’m writing my projects. In terms of corporate style, I go with whatever is already there if(it’s not) single lines;
@Isr5d
@Isr5d 24 күн бұрын
if the code is long or has multiple ifs (within the same code's scope), then I do option #4 and also refactor any ifs in within the same scope to match the syntax if any. I also sometimes do option #1 sometimes if the code is simple and short. In clarity, both seems very clear to me, but I also like to use braces where I can to know the start and end of the code, and also It helps in the editor outlining (when you expand or collapse the braces block). I only prefer Option #4 because when collapse the block, I the `if` stick to the top of the block and it's readable.
@KalleBlixtHagholm
@KalleBlixtHagholm 20 күн бұрын
We use the one-liner when it's a simple check and return early in the method, e.g "if (foo == null) return false;". Otherwise always braces on new line.
@jakubsvorc322
@jakubsvorc322 24 күн бұрын
I used to do #1 as I started with C++ and Java. Moved to #2 as I moved to C# and I stick with it. I think I just preffer visually separated singnature of method and definition. Espacially if method accepts multiple long-named parameters. I just like to "cut" (or maybe "point" would be better word selection) separated parts of method like "this is signature, this is body". I write #2 style even in typescript, if code reviewer doesn't mind. Also preffer to use multi-line curly braces, even return statements. using statements is the same way as you said - I want to "mark" the scope of disposable object. In one project I've even seen my senior colleague created block just to mark have scoped variables, like this: public void Method() { // code { //more code } }
@DmitryKandiner
@DmitryKandiner 24 күн бұрын
In general, I'm using the single-line variant for the parameter validation (i.e., if (index < 0) throw new ArgumentException(...); ). For all the rest - opening bracket at its own line.
@KeithGraves
@KeithGraves 15 күн бұрын
I like having the brackets on their own lines, so I can easily see the start and end of the block by just scanning the left side of the screen. But I also use the single line for short statements, like guard clauses at the start of a method.
@evancombs5159
@evancombs5159 24 күн бұрын
1 is acceptable only when returning. 4 is preferred in all other cases. 2 and 3 should be avoided at all costs. 2 is the worst because it forces you to read the line to understand what is going on. If you do not read the whole line you it won't be visually clear that there is a return at the end, and you might just assume you are in a 3 scenario. This is a major increase in cognitive load. 3 is bad because it breaks convention. The slight increase in cognitive load is probably mostly offset by the popularity of Javascript where most developers will recognize what is going on just fine. 1 is acceptable only when returning because we are breaking convention on purpose to create a visual context that reduces cognitive load. We always know an if statement with that shape is a guard clause returning something. Whereas if you used 4 everywhere you have to look into the brackets to know if it is a guard clause or an assignment. By giving them different shapes you immediately know the general purpose without actually reading the lines.
@Tsunami14
@Tsunami14 24 күн бұрын
Aa for parenthesis, I vastly prefer the Allman style over K&R, and will use it even for single line blocks. Much like Nick, I find that it reduces cognative load and ambiguity. However, I've been known to use single line if else for circunstances where I'm trying to group related conditionals together. ...assuming each set of condition/assigment logic is sinple enough to be expressed on a single line e.g. if (cond1) then assign1; if (cond2) then assign2; if (cond3) then assign3a else assign3b; if (cond4) then assign4; EDIT: And as another user said, I'll also put guard clauses on a single line. if (guard1) then throw new ...;
@David-id6jw
@David-id6jw 24 күн бұрын
For 1 (no braces, two lines) vs 2 (no braces, same line), I think 1 is better. Similar to with expression-bodied methods, the single-line approach can seem OK with very simple examples, but anything remotely complex makes it a mess to read, navigate, and parse. Consistency thus demands you always use the two line version, even for the simple versions which don't "need" it. For 3 (open brace on same line) vs 4 (open brace on new line), I think 4 is better. In this case, it's because having the opening brace on the same line as the condition can easily be missed when you have a complicated conditional, which means that it _looks_ like version 1 at first glance. That means that a second code line at the same indent level looks like an error (same thing as Nick explained at 6:52 for the no-brace version). It's just an annoying mental hiccup. It does save a little vertical space, which can give you a few more lines on the screen at a time, but I think I would only be comfortable using it if the no-brace versions were completely forbidden. As for with or without braces, I'm generally fine with both. I almost never use braces with guard clauses, especially if they throw exceptions. I do always use braces if there's an 'else', even if both halves are only a single line. And for the most part, I want to make sure scope is defined, the same way Nick wants it for implicit vs explicit using statements.
@qj0n
@qj0n 24 күн бұрын
7:00 - If you are worried about indentation becoming misleading, you should add an analyzer for indentation, not require other code protect against it... I personally use version 1 a lot and I use it with StyleCop and TreatWarningsAsErrors to avoid confusion. It gives very readable code
@Thompsoncs
@Thompsoncs 24 күн бұрын
Sometimes single line for simple guard clauses (these days more likely to be the throwif helpers), or when I want x ??= "some default"; but instead with string.IsNullOrEmpty/Whitespace variants so: if(string.IsNullOrEmpty(x) x = "some default";. Without brackets with statement on new line for simple things, your IDE will tell you if you mess up the scope. To quote Kevlin Henney, keep simple things simple. if (y == 1) DoSomething(); Anything more complicated obviously the standard C# brackets convention. Where possible I like to use ternaries with either one line or split depending on complexity (usually multiline), or of course the switch expression if the context fits that.
@F1nalspace
@F1nalspace 17 күн бұрын
I live in two worlds: I do C99/C++ and C# programming. For C#, i always use the preferred version of microsoft with curly braces on a new line. However, for single line statements i always remove the curly braces and leave the statement on the second line, because its much more easy to read and i can debug it much easier. In the C world, i always use the first version of the reddit post - moving the starting curly braces at the end of the condition. This also saves a bit of space, which is important for me because my libraries i write are massive in code lines due to its single-header-file-style - so i dont have to scroll that much. Regard the keyword "using" -> I do the same thing, i intentionally use the scoped version instead of the shorter one - because i want to see the code flow.
@ps2goat297
@ps2goat297 23 күн бұрын
3 or 4, I always use braces because it's easier to not make a mistake when adding code later (see heartbleed). Where the braces go depends on the project's preferences.
@WDGKuurama
@WDGKuurama 24 күн бұрын
I simply use the one line without brases depending on context. It always had been readable to me since i'm so used to it. Seing a if without anything under it makes my brain immediatly know it's an early return of some sort. i then have less code to vertically scroll (either using mouse or keyboard). If it's a complex if statement, i use the no braces multiline one (even for assignin variables). I just never use braces when i don't need them. With proper keymaps, wrapping them in braces isn't even making me loose time if i need to switch to a normal if statement with multiple line to process. Then for any issues regarding indentation.. Well i use Rider and always format my code intensively like i have ptsd so i never ever had any issues with it.
@dand4485
@dand4485 24 күн бұрын
For me the most readable/best would be: if( x ) { // secret code... } I'm more a dano-saurous, just missed when started school, we were the first class not needing to use punch cards :) But there are some practical reason and learned them in school... Often some code changes may be one liners and often within an if, there were the "Foundational Teachers" for coding in the early 80's who had run studies and found the simple edits often involved if statements and a few languages have the simple on line if, there was something like a 60% chance updating the if the programmer would fail putting in the necessare {} or Begin/End to define the actually code block/arc for the if. So the recommendation was to always put in the defined code block with {}... Another reason would assert it make it brain dead simple to see the intent of what should be in the code block and why having the opening { on a new line... Very clear. And the one other thing to help is having a new line strategically placed too often code is one long vertical stream of text and no blank lines... Defiantly should be one at the end of a function, and within "involved functions" a blank line showing/implying sub operations or portions of work with in the function... Kind of like: func() { //genearally the return object named classObject retObject = init/bad state. // setup call to funcX a few lines of code // once we looked up.... more code // and continue this pattern... looking to break up common functions... ... return retObject; }
@HarshColby
@HarshColby 24 күн бұрын
Before watching the video: I generally use if (a == b) return; To me this seems more visually understandable. To put them on separate lines would be like splitting a sentence in the middle for no reason. If I think the section of code is likely to need a breakpoint, sometimes I split it during development, then have the IDE fix it later. I've been programming for 40 years, and the original reason I always did this was that screens were tiny and getting more lines of code in the viewing area was extremely helpful. My current preference is likely based on what I go used to in the olden days. With today's monitors, space isn't a real issue, of course.
@TaSwavo
@TaSwavo 24 күн бұрын
I've always though brackets are a must - mainly because you never know when you might want to expand upon the one line and would have to add brackets at that point. And if you forget it doesn't work like your brain might be thinking. It's an easy mistake to make. As for the brackets options - I tend to use #2 now I'm writing in C# Before though we had the code in C++ and some of that code goes back over 25 years (old C code). In those days people tended to use #1. So I guess it really depends on where and when you started coding, in what language and the code you were working on that others had written, in some cases many years, earlier.
@vothaison
@vothaison 24 күн бұрын
just FYI, you can put breakpoints on the lines with the single curly open/close braces I put breakpoints there sometimes just to quickly check that my IF is hit.
@leandroteles7857
@leandroteles7857 24 күн бұрын
I never use brackets for one-line ifs, I hold the opinion that the more code is visible in your screen, the better, and brackets waste space, making your files longer and more troublesome to navigate between different parts of the code. As for the one-line vs two-line ifs, I use both. Sometimes you have an if-elseif-else, and you can make it in 3 lines, versus 6 when using line breaks, and 12 if you use all brackets. But I do that only when it fits horizontally in the screen, if the condition and/or the statement are long, I use a line break.
@maozaorox
@maozaorox 24 күн бұрын
I like to open brakets in the same line, the identation already shows me that the line below is inside something, just like python, you don't need to see the : or { to know that the line below is "another thing" because of the identation, which brings me to the second point why I like the braket system (and not the identation only system), when I see the closing braket a.k.a. } I know that that piece of code ended there and the code I could write below it will be clearly a new piece of code. For early returns and really small things I personally like the "if (success) return true" or even the braketless option since it's still clear and direct to the point of what it's really doing.
@Jaisilv
@Jaisilv 22 күн бұрын
I use multiline without curly braces for single line things like if/else and loops, etc, and curly braces below for multi lines. But my manager has complained about consistency; he prefers braces for everything, which I do understand! Plus it saves time and effort of putting in braces again when you have to expand
@Hyp3rSon1X
@Hyp3rSon1X 24 күн бұрын
I honestly just let my IDE decide. When coding, I don't manually go into a new line before typing in the opening curly brace: void doSth(){| } When I now press the Enter key: IntelliJ when coding java automatically does the first formatting approach: void doSth(){ sth(); } Visual Studio and Rider however automatically do the second formatting approach (as mentioned by you): void doSth() { sth(); } I personally don't mind any of those two approaches. But if my IDE wants me to go one way, I wont fight it.
@grzmil1
@grzmil1 23 күн бұрын
Guard clause / early exit at the top of the function, always #2 everything else #4. I follow #2 because I might have multiple reasons for early exit and I want to have each reason in separate if statement to clearly show the intent. This would sometimes take more then12 lines using #4 ... This is when I do private project. On anything else it's a team decision.
@stratokrat6290
@stratokrat6290 24 күн бұрын
Option #1 is a no-go for me. I usually use #3 or #4 depending on the coding guidelines of the project. That also often depends on the programming language. Personally I like using option #2 for guard statements like void foo(String x, String y, String z) { if(x == null) throw new IllegalArgumentException("'x' must not be null"); if(y == null) throw new IllegalArgumentException("'x' must not be null"); if(z == null) throw new IllegalArgumentException("'x' must not be null"); if(!hasPermission()) throw new PermissionException(); // .... // actual method logic }
@Blind_0wl
@Blind_0wl 24 күн бұрын
I put everything in single line only for "return early" statements when inverting if's. So it's rather: int SomeMethod (T data) { bool success = SomeCheck(data); if(!success) return -1; int result = DoSomething(data); if(result == 0) { result = DoSomethingElse(result); } return result; } But yeah, just be consistent with the rest of the code base, that's more important.
@harrismj80
@harrismj80 22 күн бұрын
I like the option #2 for guard clauses as they return only on malformed calls to the methods (null checks etc.), so they should never have more than one statement after the if check. I use #4 for everything else as it does seem to be the C# convention
@pierrehebert9743
@pierrehebert9743 22 күн бұрын
My typical preference is to put an if immediately followed by a flow statement (break, continue, return, throw, or goto) on a single line immediately followed by an empty line, or braces following language convention otherwise. I prefer the single line if as it shows the intent of an if return/break as a single statement (kind of like the ThrowIf functions) and also avoids the goto fail bug. I don't like having non-flow statement without the braces because that code is much more likely to changes, and I also view it as 2 different statements. In the end though, I mostly do this because it is a rule, and following rules gives some kind of consistency.
@Assgier
@Assgier 24 күн бұрын
It's interesting how we each prefer to be explicit or implicit in certain areas when it comes to coding. For example, you choose to always use curly braces for using statements because you prefer being explicit about your scopes. On the other hand you also use the var keyword, so in that area you choose to not be so explicit. For me it is exactly the other way around.
@LoftyCuber
@LoftyCuber 24 күн бұрын
especially in cases like where he used var in this video I wouldn't say var is not explicit. It says memory stream a few characters later.
@evancombs5159
@evancombs5159 24 күн бұрын
Then there is me preferring to be explicit in both scenarios. I only see var as a helpful development and debugging tool for when I am calling a method I'm not sure what the return type is yet or LINQ when I'm not finished building the query. It shouldn't be in production code unless required by the language. I do like the "object foo = new()" syntax because it keeps the code explicit while reducing redundancy eliminating the primary reason people use var.
@STARasGAMES
@STARasGAMES 23 күн бұрын
First of all: of course multi-line! It's a pattern that works the same across all C# - for loops, while loops, foreach loops, if statements - first line is "descriptor" and next line is actual code block. This way it's much easier to read code. Braces in separate lines help with git history in case of future changes. Adding new code before and after will only add new lines without modifying existing one. Also, if braces are already there then it's much easier to add log for debugging
@zbaktube
@zbaktube 23 күн бұрын
About the one liner: depends on the code. I may just write return success. Otherwise I like to use them at guard closes. Get out of the focus that is not important and let the logic fill the space in front of you in the screen. For me, this way it is easier to read and interpret the logic.
@TheNeozas
@TheNeozas 24 күн бұрын
I have started using c# in 2007 and I have used #4 because MSDN used this in samples and a lot of people used it as a code standard reference. Then I switched to the team which already had updated to .net 3.5 and new c# versions and someone told me that we now can use #1 and #2, it was, maybe somewhere near 2011. So for now, if team is not settled on the single solution, I'm an advocate for #2 (if the statement is short) or for #1 (if the statement is long (yes I like 120 char limits for lines)) just because from my understanding the more you see on a screen the better and bracers just eat 2 or 1 lines of code without any payload, but as long as I am using Kotlin and Swift a lot, I can understand people who prefer #3 because some does not have a chance to use #2 XD
@saberint
@saberint 24 күн бұрын
I learned programming 30+ years ago and was always taught to add braces and have it over 4 lines (I think because our compilers were less advanced).I still do it now. I find it easier to skim over when looking for issues. I don’t normal reformat other peoples code unless its an absolute mess and reading it is difficult
@asedtf
@asedtf 24 күн бұрын
My opinion on using statements is: use the explciit scoped with curlies where the disposal timing matters, use the bracketless version everywhere else where it doesnt really matter when it disooses, just that it does. Usually, almost always, the scope of the resource is "to the end of this method" anyway if you structure your code properly and apply the "methods should do one thing" principle. (I'm not advocating going overboard, just in general)
Getting Started with Event Sourcing in .NET
37:07
Nick Chapsas
Рет қаралды 15 М.
"Stop Using Properties in C#, Just Use Fields" | Code Cop #013
11:53
Can You Draw The PERFECT Circle?
00:57
Stokes Twins
Рет қаралды 72 МЛН
Зу-зу Күлпәш. Стоп. (1-бөлім)
52:33
ASTANATV Movie
Рет қаралды 1,1 МЛН
Маленькая и средняя фанта
00:56
Multi DO Smile Russian
Рет қаралды 3,8 МЛН
NO NO NO YES! (50 MLN SUBSCRIBERS CHALLENGE!) #shorts
00:26
PANDA BOI
Рет қаралды 93 МЛН
This Is Why Managers Don't Trust Programmers...
28:04
Thriving Technologist
Рет қаралды 133 М.
When You Ask the Intern to Review Your Code
4:01
Nicholas T.
Рет қаралды 483 М.
Why Developers Already Hate .NET 9
10:12
Nick Chapsas
Рет қаралды 70 М.
We should use this amazing mechanism that's inside a grasshopper leg
19:19
The Pattern You MUST Learn in .NET
20:48
Nick Chapsas
Рет қаралды 74 М.
Stop Using the Worst Way to Loop Lists in .NET!
9:35
Nick Chapsas
Рет қаралды 41 М.
Stop using the HttpClient the wrong way in .NET
10:14
Nick Chapsas
Рет қаралды 181 М.
Solid Programming - No Thanks
32:00
ThePrimeTime
Рет қаралды 209 М.
Await Async Tasks Are Getting Awesome in .NET 9!
9:24
Nick Chapsas
Рет қаралды 82 М.
Can You Draw The PERFECT Circle?
00:57
Stokes Twins
Рет қаралды 72 МЛН