The Right Way to Write if Statements in C#

2024 ж. 25 Сәу.
46 872 Рет қаралды

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

Пікірлер
  • 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.

    @gianvitodifilippo@gianvitodifilippo13 күн бұрын
    • 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.

      @kvurit@kvurit13 күн бұрын
    • Exactly, same page

      @TuxCommander@TuxCommander13 күн бұрын
    • YES!

      @paulkoopmans4620@paulkoopmans462013 күн бұрын
    • 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.

      @TennysonHull@TennysonHull13 күн бұрын
    • 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 😄

      @gianvitodifilippo@gianvitodifilippo13 күн бұрын
  • 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).

    @TheCzemike@TheCzemike13 күн бұрын
    • exactly. that's where the real problems are

      @xybersurfer@xybersurfer12 күн бұрын
    • @@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

      @cgeorgescu72@cgeorgescu7212 күн бұрын
    • ​@@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!

      @nicholaspreston9586@nicholaspreston958612 күн бұрын
    • Are you still laughing?

      @adassko6091@adassko609112 күн бұрын
  • 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.

    @smathlax@smathlax13 күн бұрын
    • 👍👍

      @luc9volts@luc9volts13 күн бұрын
    • Fully agree. Nick's argument here is "if you do a dumb thing it looks dumb", but the code formatter will fix that.

      @Stanbeard@Stanbeard13 күн бұрын
    • 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.

      @user-dy8dl6xu5w@user-dy8dl6xu5w13 күн бұрын
    • 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.

      @JamieTwells@JamieTwells13 күн бұрын
    • ​@JamieTwells Haha I didn't even notice the editor fighting 😂

      @smathlax@smathlax13 күн бұрын
  • 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.

    @cdoubleplusgood@cdoubleplusgood13 күн бұрын
    • "Dont make me think" is pretty subjective, hence not appropriate for a rule.

      @marino3034@marino303412 күн бұрын
    • dont like the fact that if () return 0; is being expanded into 4 lines.. Few checks and you have to scroll code :)

      @elpe21@elpe2112 күн бұрын
    • 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

      @thedave1771@thedave177112 күн бұрын
  • 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.

    @AkariTheImmortal@AkariTheImmortal13 күн бұрын
  • 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.

    @betterlifeexe4378@betterlifeexe437813 күн бұрын
    • 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

      @StarfoxHUN@StarfoxHUN13 күн бұрын
    • That's ok. It's ok to be wrong. :D

      @WarrenGarabrandt@WarrenGarabrandt13 күн бұрын
    • ​@@StarfoxHUNoh no way, adding two more brackets, what a waste of time 😢😢

      @LilPozzer@LilPozzer13 күн бұрын
    • @@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.

      @betterlifeexe4378@betterlifeexe437813 күн бұрын
    • @@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).

      @joshpatton757@joshpatton75713 күн бұрын
  • 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.

    @billy65bob@billy65bob13 күн бұрын
  • 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.

    @sasukesarutobi3862@sasukesarutobi386213 күн бұрын
    • @@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

      @TheNeozas@TheNeozas13 күн бұрын
    • @@TheNeozas good point. not that it justifies them using crappy IDEs

      @xybersurfer@xybersurfer12 күн бұрын
    • @@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.

      @sasukesarutobi3862@sasukesarutobi386212 күн бұрын
  • 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.

    @ApacheGamingUK@ApacheGamingUK13 күн бұрын
  • Return success?

    @berry212@berry21213 күн бұрын
    • what if there is more than one condition?

      @andreyz3133@andreyz313313 күн бұрын
    • @@andreyz3133 ad switch ;)

      @m057d0p3@m057d0p313 күн бұрын
    • :) 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.

      @WilliamLeeSims@WilliamLeeSims13 күн бұрын
    • if (!success ^ true != false) { return success ? true : true; }

      @mirabilis@mirabilis13 күн бұрын
    • 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

      @tcortega@tcortega13 күн бұрын
  • 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.

    @Fajerkoks@Fajerkoks13 күн бұрын
  • 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?

    @jongeduard@jongeduard13 күн бұрын
  • 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.

    @wesplybon9510@wesplybon951013 күн бұрын
  • 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.

    @DanGolick@DanGolick13 күн бұрын
  • I'm consistent. Blocks - no matter the size - are always surrounded by curlies, and curlies in C# are always on their own line.

    @modernkennnern@modernkennnern13 күн бұрын
    • C# is not java !!!

      @paulomfgoncalves@paulomfgoncalves13 күн бұрын
    • 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

      @AnsisPlepis@AnsisPlepis13 күн бұрын
    • 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.

      @TazG2000@TazG200012 күн бұрын
    • @@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!!!

      @paulomfgoncalves@paulomfgoncalves12 күн бұрын
    • @@paulomfgoncalves So are you under the impression that every work group using C# uses the same style? And only uses C#?

      @TazG2000@TazG200012 күн бұрын
  • 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.

    @demarcorr@demarcorr13 күн бұрын
    • 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? 🧌

      @DoubleBullet@DoubleBullet13 күн бұрын
    • @@DoubleBullet ...... what?

      @demarcorr@demarcorr12 күн бұрын
    • @@demarcorr sorry

      @DoubleBullet@DoubleBullet12 күн бұрын
  • 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".

    @WilliamLeeSims@WilliamLeeSims13 күн бұрын
    • @@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.

      @JohnPeter-yf5jf@JohnPeter-yf5jf13 күн бұрын
    • @@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.

      @joshpatton757@joshpatton75713 күн бұрын
    • 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.

      @evancombs5159@evancombs515913 күн бұрын
  • 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?

    @JoshOlsonDev@JoshOlsonDev13 күн бұрын
  • 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

    @emloq@emloq13 күн бұрын
  • 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

    @antonzhernosek5552@antonzhernosek555213 күн бұрын
  • 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.

    @brianviktor8212@brianviktor821213 күн бұрын
  • 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.

    @AnatoliiMakarov@AnatoliiMakarov13 күн бұрын
  • 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).

    @DemoBytom@DemoBytom13 күн бұрын
  • 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.

    @1992jamo@1992jamo13 күн бұрын
    • 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.

      @pilotboba@pilotboba13 күн бұрын
    • @@pilotboba I can't understand how this happens if you're vigilant with indentation

      @1992jamo@1992jamo13 күн бұрын
    • @@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.

      @pilotboba@pilotboba13 күн бұрын
    • 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.

      @TehKarmalizer@TehKarmalizer11 күн бұрын
    • @@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.

      @pilotboba@pilotboba9 күн бұрын
  • 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.

    @renynzea@renynzea13 күн бұрын
  • 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.

    @donr484@donr48413 күн бұрын
  • 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.

    @Isr5d@Isr5d13 күн бұрын
  • 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.

    @CodeOptimism@CodeOptimism13 күн бұрын
  • 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 ;)

    @yetanotherdex@yetanotherdex13 күн бұрын
  • 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

    @markmundy9582@markmundy958213 күн бұрын
  • 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.

    @codingbloke@codingbloke13 күн бұрын
  • 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.

    @Deathflame82@Deathflame8211 күн бұрын
  • 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.

    @laurentallenguerard@laurentallenguerard13 күн бұрын
  • 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.

    @aldelaro@aldelaro13 күн бұрын
    • 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.

      @orionsteel5921@orionsteel592112 күн бұрын
  • 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 } }

    @jakubsvorc322@jakubsvorc32213 күн бұрын
  • 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.

    @WarrenGarabrandt@WarrenGarabrandt13 күн бұрын
  • 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#

    @GirlAteDeath@GirlAteDeath13 күн бұрын
    • 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.

      @sacalbal@sacalbal13 күн бұрын
  • 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.

    @logicalsparrow2130@logicalsparrow213013 күн бұрын
  • 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.

    @JamieTwells@JamieTwells13 күн бұрын
    • Same. Indentation for readability and VS autoinserts it on Enter anyways.

      @klocugh12@klocugh1213 күн бұрын
    • Totally agree, and this whole discussion is pointless

      @nishudar@nishudar13 күн бұрын
  • 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.

    @vertxxyz@vertxxyz13 күн бұрын
  • 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.

    @WDGKuurama@WDGKuurama13 күн бұрын
  • 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.

    @marcusmajarra@marcusmajarra13 күн бұрын
  • 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.

    @MorcamOne@MorcamOne13 күн бұрын
  • 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.

    @CuriouslyContent@CuriouslyContent13 күн бұрын
  • You mentioned your usual syntax when using streams. How often are you using them in your work and in what situations would you decide to use them?

    @aaronhevenstone9697@aaronhevenstone969713 күн бұрын
  • I use #1 when i return literals (e.g. null) or when i want to make a single mathod call and it's signature is not that long. It reads better in my opinion when the statement is very concise. I use #2 more consistently when throwing exception in guards or calling methods with a long signature. I never use #3, when i add brackets I follow Microsoft's convention. #4 is for all other cases, where the if enters a multi-statement block (obviously) or when the single method call/return statement spans too many characters and I have to subdivide it on multiple lines (for instance, say, a method with 6-7 parameters). I don't really agree with the reasons you gave for why #1 and #2 are confusing, since whoever uses wrong tabulation and writes a second statement after a semicolumn without starting a new line clearly has a very different opinion on coding as a whole, not just brackets

    @acciaio@acciaio12 күн бұрын
  • 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.

    @tellur808@tellur80813 күн бұрын
  • 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 !

    @Moosa_Says@Moosa_Says12 күн бұрын
  • 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

    @perdonomai8060@perdonomai806013 күн бұрын
  • 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.

    @ErazerPT@ErazerPT13 күн бұрын
  • 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.

    @slipoch6635@slipoch663513 күн бұрын
  • if () { means the closing bracket is in a different column, I don't like that.

    @TonyWhitley@TonyWhitley13 күн бұрын
    • This. Always when IDE screams about missing braces I check columns.

      @TheTigerus@TheTigerus13 күн бұрын
  • 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.

    @colindawson4818@colindawson481813 күн бұрын
  • 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 :)

    @rainbowsprinklez@rainbowsprinklez13 күн бұрын
  • I first used to prefer no linefeed before brace, but with experience, i figured linefeed to be more convenient. So I switched. I somethime use one-lined if, but in only one condition : at the beggining of a method in preconditions. The question is, what is worth to read ? In a method body, you want to read how the code is running, you need to see 1 instruction per line. In a method precondition, you need to figure out when does the method applies or when you get an error. I personnaly think it's more readable if you have one condition per line. Now that some Exception classes got functions to raise errors on some conditions, i prefer using it instead of an if. If such a method does not I write it. for example I would have written : public void DoSomething(int arg) { if (variable = 0) { throw new ArgumentOutOfRangeException(valueName, value, $"{valueName} must be lesser or equals than {max}"); } return value; } I'd rather write : public void DoSomething(int arg) { variable.MustBeGreaterOrEqualsThan(0); variable.MustBe(x=> x != 10); ... method body ... } Which better fits guidelines and is still greatly readable.

    @warny1978@warny197813 күн бұрын
  • 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.

    @TennysonHull@TennysonHull13 күн бұрын
  • 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.

    @HarleyPebley@HarleyPebley13 күн бұрын
  • 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.

    @sebiederer@sebiederer13 күн бұрын
  • As for the using, I've happened to (ab)use the disposable pattern, implementing it on a struct that adjusts the state of my object and reverts its state effect upon disposal. It's efficient iirc in terms of being actually statically compiled into a concrete Dispose() call without virtualizing via the interface, and the scope spans throughout the entire method anyway. Or maybe in cases where you don't care about the exact scope and the time at which your disposable gets disposable, as in it has no effect on your application, then that block-scoped using feels very nice. Again, those are very niche cases and like any feature it should be used very carefully.

    @AlFasGD@AlFasGD13 күн бұрын
  • 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; }

    @dand4485@dand448513 күн бұрын
  • I never use option 1 (in your video). I hate it. I would rather prefer option 2 than option 1 for the same reason as you that if adding another line of code just after option 1 you don't know if was suppose to be part of the if statement or it's another peace of code. For that reason alone I try to use option 4 (the Microsoft way) anywhere. The only reason I also prefer option 2 is when debugging code and I have to debug line by line the simple "1 liner" makes it easier to debug if you know the expression in the if statement won't get hit. For example in loops where you want to hit a certain condition or want to skip until a certain condition is met like: foreach(User user in Users) { if (user.Initials != "nc") continue; } I know I can use a breakpoint and set a condition etc. etc. but I using condition doesn't always work in our codebase where the above line does. So to wrap things up. I use option 4 almost everywhere but option 2 where the condition is usually something that I wouldn't hit and make it easier to debug line by line or the condition is very obvious like the exemple above.

    @CRBarchager@CRBarchager13 күн бұрын
  • 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 ...;

    @Tsunami14@Tsunami1413 күн бұрын
  • What do you think about the multiple return statements? I personally prefer only one per method.

    @luckynikooo@luckynikooo13 күн бұрын
  • 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).

    @petedavis7970@petedavis79704 күн бұрын
  • 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.

    @leandroteles7857@leandroteles785713 күн бұрын
  • exclusively for single line if statements, primarily early return / throw checks, i put the curly braces and everything in between them all on the same line with the if statement itself. I had it drilled into me to always use braces just in case you add more code later but I hate having a simple "if null throw" or "if 0 return" or whatever taking up 4 entire lines. Otherwise I put both braces on their own line, entirely because that's the default in VS studio. Otherwise I'd probably put the opening brace on the same line as the if, but I don't care enough to go change settings or go against the MS style guides.

    @salmelo16@salmelo1613 күн бұрын
  • 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.

    @maozaorox@maozaorox13 күн бұрын
  • 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

    @STARasGAMES@STARasGAMES13 күн бұрын
  • I prefer braced versions heavily over unbraced. If unbraced, then only single-line if with a short condition and body. If it gets long → braces & break. As for the line-break in front of the opening brace, I don't really care and use what ever is previously present. However, I get the type-setting argument: In type-setting black-white-balance is a thing, with good balancing making reading supposedly easier. And with line-break before the opening brace the whitespace in the resulting text is more evenly spread out. For the other version, if some blocks are nested, they tend to "clump" at the top and have a lot of whitespace at the bottom with all the single-line closing braces.

    @ando_rei@ando_rei13 күн бұрын
  • 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.

    @David-id6jw@David-id6jw13 күн бұрын
  • As an introvert, I will fight against "brace-cuddled else ifs" at all cost.

    @JohnWilliams-gy5yc@JohnWilliams-gy5yc13 күн бұрын
  • 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.

    @marccygnus@marccygnus13 күн бұрын
  • 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#.

    @MarquisKurt@MarquisKurt13 күн бұрын
  • 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.

    @THPieta@THPieta7 күн бұрын
  • 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.

    @evancombs5159@evancombs515913 күн бұрын
  • 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.

    @darkwater234@darkwater23413 күн бұрын
  • 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

    @zbaktube@zbaktube13 күн бұрын
  • 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.

    @F1nalspace@F1nalspace6 күн бұрын
  • The correct answer is to use the one that your shop recommends in their code standards. My shop recommends the brackets on their own lines for readability. Personally, I prefer the single line for efficiency. Unless its a complex statement.

    @jasonmurdick9864@jasonmurdick986412 күн бұрын
  • 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.

    @wtflolomg@wtflolomg13 күн бұрын
  • 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 :).

    @dde-fz7ih@dde-fz7ih6 күн бұрын
  • 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

    @TheNeozas@TheNeozas13 күн бұрын
  • For C# I go with option #4, ALWAYS, even for single line statements. Never not using braces and braces always starts on a new line. Same with using-statements: always with braces; I want to see the scope without any mental load. Using braces on a new line follows the good old MS conventions and is consistent with how I write any other other braced/scoped statements like classes and methods. Using the same coding style everywhere makes everything easier to read and by sticking to one style I don't have to think about using a special style for some specific cases based on something so arbitrary as the number of lines of code. The ONLY exception for always using braces is that I'll always go with file scoped namespaces. But the only reason for this is that I never ever use more than one namespace in a single file anyway. And, I'll also go with the top-level statement for Program.cs. For other languages I'll go with whatever seems to be the most used conventions. Fx for javascript, I'll always go for option #3 for everything.

    @spacemanjack777@spacemanjack77713 күн бұрын
  • 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.

    @HarshColby@HarshColby13 күн бұрын
  • The only time I put curlies on their own line, is for class declarations. It seems like such a waste to have a whole line for a single curly bracket. I learned this style for c# about 9 years ago from reading another persons code. I didn't like it at first, but after I had used it for a couple months I could never go back. Also, the only time I don't use curlies, is when it's a single line, like `if (argument is null) throw new ArgumentNullException(nameof(argument));` So I always use 1, unless the project is using 2 or some other style, I'll mirror the style of the project I'm working on. Like they said, consistency is more important than personal preference. This is how I ended up learning about #1 and preferring #1.

    @kelton5020@kelton502013 күн бұрын
  • 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.

    @DimasMessias-kl4ic@DimasMessias-kl4ic13 күн бұрын
  • 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.

    @ClawGr@ClawGr12 күн бұрын
  • 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.

    @HollandHiking@HollandHiking7 күн бұрын
  • If( x) { } treats the braces as a burden rather than an asset. As if programmer was saying I wish these weren't here. Is if( x ) return y; truly the same as if( x ) { return y; } Do both create a scope that contains return y? If not, does that scope have a cost?

    @jpboy1962@jpboy196213 күн бұрын
  • I write both C# and TypeScript all day, every day. K&R indentation and I use all those styles of "if" and more.

    @rapzid3536@rapzid353612 күн бұрын
  • 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.

    @Assgier@Assgier13 күн бұрын
    • 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.

      @LoftyCuber@LoftyCuber13 күн бұрын
    • 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.

      @evancombs5159@evancombs515913 күн бұрын
  • 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 :)

    @___bf____@___bf____13 күн бұрын
    • perfect

      @haffneralex@haffneralex3 күн бұрын
  • Generally I hate the "standard" C# way of having opening brackets on a separate line. I consider the, I guess Java, way of writing opening brace next to the statement and then putting a new line way more inherently tied with the statement, since the indentation, IDE vertical lines and the closing brace will all guide me to the statement that opens given code block. If I put a newline between statement and the opening brace, I just feel that someone might put some new statement between, changing the semantics of the code. It's, of course, not really something that happens, but it just feels off to me. Regarding no brace approaches, I use them only if I write something just for myself and don't plan on expanding on it. I wouldn't cast these on other developers to read through, since I myself don't like these when I read someone's code. I don't feel like it's more difficult to comprehend or to see the scope, but it is more steps for me if I want to expand inside this scope, because I need to add braces myself. If I use these, I usually go for full oneliner if the block is something like "return true" or similar really short, easy to comprehend expression. If it is longer, for example ternary operation, function call with multiple arguments, or anything that spans multiple words but still is just "one line", I put it on it's own line. In addition, similarly, I don't like my if-else statements to refactor as with closing brace of if on one line, else and it's opening brace on the next, and code on third. I prefer having } else { all on one line and then the scope of the else-block starting on the next. My argument for this is the same - I consider the cues that most IDEs provide more leading towards the keywords and which block are you currently in. The first approach is not dissimilar, but it feels like way more clutter while reading the code.

    @Wllader@Wllader13 күн бұрын
  • 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 }

    @stratokrat6290@stratokrat629013 күн бұрын
  • 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.

    @drndn@drndn13 күн бұрын
    • 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.

      @cgeorgescu72@cgeorgescu7212 күн бұрын
  • 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;

    @nicktech2152@nicktech215213 күн бұрын
  • 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.

    @Thompsoncs@Thompsoncs13 күн бұрын
  • 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.

    @DmitryKandiner@DmitryKandiner13 күн бұрын
  • One line no brackets is peak for guard clauses. I can't think of even one instance where I was confused about the scope. If it's all on one line it's even more clear.

    @yoyoyopo5@yoyoyopo513 күн бұрын
    • Yes! One line for guard clauses. Right at the top of the method. Absolutely!

      @EnergyBars.Trading@EnergyBars.Trading13 күн бұрын
  • 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.

    @Blind_0wl@Blind_0wl13 күн бұрын
KZhead