I am using ReSharper to refactor my code, and one of the suggestions of ReSharper is to use a respective branch instead a if statement that is always true.
If I have
if (myVar != null){
//code
}
And I apply the respective branch the code is like the following
{
//code
}
Is this a short cut of an if statement?
What is this used for?
What is the difference between the cutely brackets and nothing?
Thanks in advance.
The block is required to stay there, or semantics would change.
The scope of variables declared inside the branch block would change when you remove the braces. Potentially with conflicting/hiding (lambda) variables this would lead to surprises.
To remove the braces, position the cursor on either one and hit Alt-Enter, 'Remove Braces'
Reintroduce braces: select block of code, Ctrl-Alt-J, 7 to surround with block :)
In ReSharper 6.0 this command also removes braces if you don't have variable declarations inside.
Related
I was looking at this link for clarification on the Linux Kernel Coding Style (https://www.kernel.org/doc/html/v4.15/process/coding-style.html#placing-braces-and-spaces)
However I do not see any explanation on how to format nested if-statements. Here is the chunk of code that I am questioning:
if (cond1) {
if (cond2) {
1 line of code...
}
} else {
1 line of code again...
}
Does the nested if statement need the curly braces, even though it only has 1 line of code? I know that the else statement does need the curly braces, since that is what the docs specify. I am trying to avoid any styling issues that result in my commit getting rejected. Thank you.
As #Tsyvarev mentioned - there is no specific conventions for nested if-statements.
Regarding single-line if-statements - you don't have to. Keep in mind though that one of the main goals of conventions is to maintain code readability. In the end, your code should be readable. If a curly braces makes your code more readable, even if it is only one line - then use curly braces.
As every new programer starting in Go 1st think you see is, strict code format.
Means:
//Valid
func foo(){
}
//Invalid
func foo()
{
}
Same goes for if-else that else should be in same line where if ends, like:
//Valid
if{
}else{
}
//Invalid
if{
}
else{
}
we get below error:
syntax error: unexpected else, expecting }
I have checked the spec spec, but not able to find why.
The only explanation I'am getting is its mandatory.
Can anyone explain us why this is mandated does this have any reason? if any.
UPDATE
I think i have mention this already that "I know lang say so", Question is WHY?
Why to go this length to make it compile time error, what problems it was posing if we don't do this?
The language was designed as such and the reason is outlined in the FAQ.
https://golang.org/doc/faq
Why are there braces but no semicolons? And why can't I put the opening brace on the next line?
o uses brace brackets for statement
grouping, a syntax familiar to programmers who have worked with any
language in the C family. Semicolons, however, are for parsers, not
for people, and we wanted to eliminate them as much as possible. To
achieve this goal, Go borrows a trick from BCPL: the semicolons that
separate statements are in the formal grammar but are injected
automatically, without lookahead, by the lexer at the end of any line
that could be the end of a statement. This works very well in practice
but has the effect that it forces a brace style. For instance, the
opening brace of a function cannot appear on a line by itself.
Some have argued that the lexer should do lookahead to permit the
brace to live on the next line. We disagree. Since Go code is meant to
be formatted automatically by gofmt, some style must be chosen. That
style may differ from what you've used in C or Java, but Go is a
different language and gofmt's style is as good as any other. More
important—much more important—the advantages of a single,
programmatically mandated format for all Go programs greatly outweigh
any perceived disadvantages of the particular style. Note too that
Go's style means that an interactive implementation of Go can use the
standard syntax one line at a time without special rules.
Go inserts a ; at the end of lines ending in certain tokens including }.
Since if {...} else {...} is a single statement, you can't put a semicolon in the middle of it after the first closing brances i.e. }, hence the requirement to put } else { on one line is mandatory.
I hope it answers your question.
I'm interested in putting an opening brace for functions (but not if statements and other contexts). For example
void foo()
{
...
}
Flamewars aside, is there a good rationale for not doing this? Although I use same-line open-brackets for if/else and smaller blocks, I think in this case visual organization of larger units of code (functions/methods/classes/structs) can trump perfect consistency.
Moreover, how do I get clang-format to follow this style?
As the documentation says, invoke clang-format with -style=file, and use a .clang-format file placed in an enclosing directory to customize style options. The format style option specifying brace placement is called BreakBeforeBraces. From the docs,
BreakBeforeBraces (BraceBreakingStyle)
The brace breaking style to
use.
Possible values:
BS_Attach (in configuration: Attach) Always attach braces to surrounding context.
BS_Linux (in configuration: Linux) Like Attach, but break before braces on function, namespace and class definitions.
BS_Stroustrup (in configuration: Stroustrup) Like Attach, but break before function definitions, and ‘else’.
BS_Allman (in configuration: Allman) Always break before braces.
BS_GNU (in configuration: GNU) Always break before braces and add an extra level of indentation to braces of control statements, not to
those of class, function or other definitions.
The style that matches your description is BS_Stroustrup. Add the following entry to your .clang-format
BreakBeforeBraces: Stroustrup
In addition to the docs, clangformat.com lists all the options and illustrates many of them with examples.
Pradhan has an excellent answer, but you may find that you get breaks where you do not want them (as I found).
There is another option, "Custom", in at least clang-format versions 3.8 and 5 (I'm using 3.8 and found BS_Custom in the 5 docs). With this, you can specify in BraceWrapping what you want, including an "AfterFunction" option.
In the following example excerpt, I have listed others as true/false since the OP's question only specifies AfterFunction (i.e. "before opening brace of a function"):
BraceWrapping:
AfterClass: true
AfterControlStatement: true
AfterEnum: true/false
AfterFunction: true
AfterNamespace: true/false
AfterObjCDeclaration: true/false
AfterStruct: true/false
AfterUnion: true/false
BeforeCatch: true/false
BeforeElse: true/false
IndentBraces: true/false
BreakBeforeBraces: Custom
I have tested this with my configuration and it gives finer-grained control of brace breaking.
I have an issue.
I need to modify java "if/else/for/while/do statements should always use curly braces" coding rule into sonar Quality Profiles.
if/else/for/while/do statements should always use curly braces Not
using curly braces could be error-prone in some cases. For instance in
the following example, the two statements seems to be attached to the
if statement whereas this is the case only for the first one:
if (condition) // Non-Compliant
executeSomething();
checkSomething();
if (condition) { // Compliant
executeSomething();
}
checkSomething();
I need to extend it with adding one exclusion.
I should to keep this rule but add exception:
if (Logging.ENABLED) Logging.*
this expression should be ignored by this rule. Its mean that alarm should not appear when i write e.g.
if (Logging.ENABLED) Logging.logThrowable(LOG_TAG, e);
Could you be so kind how exactly step by step i can do it.
Thanks!
You can set an exclusion. See http://docs.codehaus.org/display/SONAR/Narrowing+the+Focus#NarrowingtheFocus-IgnoreIssues ("Ignore Issues in Blocks" section). Start block can be "Logging.ENABLED" and End block can be "$". The only drawback for now is that it'll ignore all issues on this line. Feel free to vote for http://jira.codehaus.org/browse/SONAR-5122 if it's not ok with you.
exampleObject = new Panel{
if (this.exampleField ===1) {
}
}
Cursor is on one of the inner braces. What is a shortcut for going to one of the outside braces?
I only posted the simple example for clarity of the question. My code is much more messy with dozens of blocks within a big block. A simple search will not suffice.
I don't know a single key combo, but
<shift>-<right>, <ctrl-F>, <enter>
will take you to the end of the outer block if you are on the trailing brace, and
<shift>-<right>, <ctrl-F>, <shift>-F3
will take you to the beginning if you are on the leading one.