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.
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 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.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
Ever since I first wrote
if ($a = 5) {
# do something with $a, e.g.
print "$a";
}
and went through the normal puzzling session of
why is the result always true
why is $a always 5
until I realized, I'd assigned 5 to $a, instead of performing a comparison.
So I decided to write that kind of condition above as
if (5 == $a)
in other words:
always place the constant value to the left side of the comparison operator, resulting in a compilation error, should you forget to add the second "=" sign.
I tend to call this defensive coding and tend to believe it's a cousin to defensive-programming, not on the algorithmic scale, but keyword by keyword.
What defensive coding practices have you developed?
One Week Later:
A big "thank you" to all who answered or might add another answer in the future.
Unfortunately (or rather fortunately!) there is no single correct answer. For that my question was to broad, asking more for opinions or learnings of experience, rather than facts.
Always use braces:
if(boolean)
oneliner();
nextLineOfCode();
is not the same as:
if(boolean)
{
oneliner();
}
nextLineOfCode();
If oneliner() is a #defined function, and it isn't defined then your next line of code suddenly becomes subject to the if(). Same thing applies to for loops etc. With braces then the next piece of code never unintentionally becomes conditional on the if/for etc.
The top 3 defensive coding practices I employ are
unit testing
unit testing
unit testing
There is no better defense for the quality of your code than a good unit test to back you up.
This is a simple and obvious one, but I NEVER EVER NEVER repeat the same string constant twice in my code, cause I KNOW that if I do I will be spelling one of them wrong :) Use constants, people!
Always put curly braces after an if/for/while ... even if there's only one single statement after. BTW D. Crockford thinks it's better too: Required blocks
When comparing a string with a constant, write
if ("blah".equals(value)){}
instead of
if (value.equals("blah")){}
to prevent a NullPointerException. But this is the only time I use the suggested coding-style (cause "if (a = 1)..." is not possible in Java).
One of the things I always try to remember when I am in the Javascript world is to always start the return value of a function on the same line as the return key word.
function one(){
return {
result:"result"
};
}
function two(){
return
{
result:"result"
};
}
These 2 functions will not return the same value. The first function will return an Object with a property results set to "result". The second function will return undefined. It's a really simple mistake and it happens because of Javascript's over-zealous Semi-Colon Insertion strategy. Semi-colons are semi-optional in Javascript and because of this the Javascript engine will add semi-coons where it thinks it's should be. Because return is actually a valid statement a semi-colon will be inserted after the return statement and the rest of the function will essentially be ignored.
From my blog:
Think positive and return early plus avoid deep nesting. Instead of
if (value != null) {
... do something with value ...
}
return
write
if (value == null) {
return
}
... do something with value ...
Avoid "string constants" (i.e. the same text in quotes in more than one place). Always define a real constant (with a name and an optional comment what it means) and use that.
Personally, I dislike this defensive style, it makes the code hard ro read.
VC compiler warning level 4 will spot this (possible) error.
"warning C4706: assignment within conditional expression"
You can enable just this specific compiler warning, at any level:
#pragma warning(3,4706)
Always initialize variables
Use const wherever I can (without using mutable)
Avoid bare dynamic allocation of memory or other resources
Always use curly braces
Code use-cases and tests for any class before coding implementation
Turn on as many useful warnings as I can (-Wall -Wextra -ansi -pedantic -Werror at a minimum)
Use the simplest tool that solves the problem (in my current environment, that's bash -> grep -> awk -> Python -> C++).
I stopped using languages where you can do
if a = 5: print a
This has saved me tons of headaches =).
On a more serious note... I now always write the curly braces right after I write my ifs and for loops, and then fill them in afterwards. This makes sure my brackets are always aligned.
Returning a copy of a mutable object, i.e. a copy of an array, not the mutable object itself.
Couple things:
Yes, the 1-line blocks. Use the braces... heck, most good IDE's will make em for you.
Comment your code after you write it, or re-read your comments if you did it ahead of time. Make sure your code still does what the comments say.
Unit testing is a great fallback to re-reading your code.
Always log an exception... or, NEVER catch an exception without saying so, at least in debug.
Avoid unnecessary test.
Example
if(bool == true)
Pointer checks if(pointer)
EDIT:
if(pointer) is not readable so nowadays I prefer if(NULL != pointer)
Installed Resharper ;)
Then I don't need to write "5 == a" to get warned if I did something wrong :)