So I know it's considered somewhat good practice to always include curly braces for if, for, etc even though they're optional if there is only one following statement, for the reason that it's easier to accidentally do something like:
if(something == true)
DoSomething();
DoSomethingElse();
when quickly editing code if you don't put the braces.
What about something like this though:
if(something == true)
{ DoSomething(); }
That way you still take up fewer lines (which IMO increases readability) but still make it unlikely to accidentally make the mistake from above?
I ask because I don't believe I've ever seen this style before for if or loops, but I do see it used for getter and setter in C# properties like:
public string Name
{get;set;}
Not asking what's best since that's too subjective, but rather just whether this would be considered acceptable style and if not, why not.
An opening curly brace should never go on its own line and should always be followed by a new line. A closing curly brace should always go on its own line, unless it's followed by else. Always indent the code, 2 spaces, inside curly braces.
While curly brackets are mainly used to group several lines of codes, it will still work without error if you used it for a single line. Some programmers prefer this method as a way of organizing codes to make it look clearer, especially in conditional statements.
Yes it is not necessary to use curly braces after conditions and loops (functions always need them) IF and only if there is just one statement following. In this case it automatically uses the next statement.
I've always said – using single line ifs is dangerous, because a junior (or even a seasoned) developer might make a mistake and add an extra line of code which will not be executed in the if block.
When I come across a one-line if statement, I usually skip the curlys and keep everything on the same line:
if (something == true) DoSomething();
It's quick, easy, and saves space.
Instead of:
if(something == true)
{ DoSomething(); }
Do this:
if(something == true) { DoSomething(); }
I tend to put opening braces on their own line like this:
if (condition)
{
statement;
statement;
}
So seeing something like:
if (condition)
statement;
statement;
stands out as wrong right away. If I only have one statement I just leave it as
if (condition)
statement;
and put the braces in later if I have an extra statement to add. I don't really see any room for confusion.
Putting the statement on the same line as the condition is a bad habit to get into, since when you're debugging, most debuggers count the whole thing as one line. (I realize that in C# this is not the case).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With