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 2 years ago.
Improve this question
I never decided on what the best way is to comment if-then-else constructs, so I never standardized on a consistent way to comment them.
I appreciate any insights.
Some options:
a)
if (blabla) {
// this comment explains what happens in the IF case
dothis();
} else {
// this comment explains what happens in the ELSE case
dosomethingelse();
}
drawback: in case of multiple dothis() statements, I like to comment the major blocks, and in that case it isn't always clear if the IF-comment belongs to the first dothis() block or to the whole IF case
or b)
if (blabla) { // this comment explains what happens in the IF case
dothis();
} else { // this comment explains what happens in the ELSE case
dosomethingelse();
}
drawback: only works for short comments. I usually comment IF-THEN-ELSE constructs if the IF and ELSE case isn't directly clear from the code, which typically requires a comment longer than one line.
or c)
// if the following happens
if (blabla) { // then do this
dothis();
} else { // or else do this
dosomethingelse();
}
PS: I know about "the code should be self explanatory", but this isn't always the case...
For me, a comment above the IF explains the IF statement itself. For example, if the condition being tested is particularly complex.
A comment in the block below the IF or ELSE describes what's going once the condition has been evaluated and a choice made.
So like this:
//Is this a favoured customer and do we have a promotion?
if customer.special() and monthly.hasOffer() {
//Add discount
invoice.addDiscount();
}
else {
//Add note about favoured customer scheme
invoice.addNotes(JOIN_OUR_DISCOUNT_SCHEME);
}
I never gave it very much thought; personally and when required I have put comments above the IF and ELSE statements. This gives me nice separation between the comments about the branch statements and comments about the code.
// comment about the if statement
if (expression)
{
// comment about the code
doSomething();
}
// comment about the else statement
else
{
// comment about the code
doSomethingElse();
}
I also note that I am the only answer so far to use the "open curly brace style", which might be a throw back to my Pascal days although I do prefer the visual justification of begin and ends of code blocks, so my comment style may not work for the "closed curly brace style community.
I'd do case a) but with an extra bit of whitespace:
if (blabla) {
// This explains the whole if case
// Can comment here for specific block comments
doThis();
} else {
// This explains the else case
// Same again
doSomethingElse();
}
Personally, I findi it better to write code that doesn't require little comments that say "about do do x", followed by "DoX()". If necessary, rather than write a comment saying "do x because of y", I'd prefer to write a method named "DoXBecauseOfY". If later refactoring removes the "BecauseOfY" part, then it still makes better sense to put a comment before the if statement, documenting the overall logic.
Of course, you then need to reduce the amount of code within each branch to the point where you can read the entire if statement at once.
Use what makes sense to you, I guess (unless you're working under a coding standard that specifies commenting style). Personally I don't use (c) because it's inconsistent between the first and following cases. I do occasionally use (b) when a short comment will do but generally I prefer (a). If I'm commenting several sub-blocks within the if block, I might leave a blank line after the case comment:
if (blabla) {
// here's a comment about this case
// comment about this bit of code
bit_of_code();
// comment about this other bit of code
other_bit_of_code();
}
and so on.
// Not very much sure, but here is a snippet of my code
// tweak URL as per query params and hash index positions
if (hasQueryParams && hashPos > -1) {
// both query params and hash available
...
...
} else if (hasQueryParams) {
// only query params available
...
...
} else if (hashPos > -1) {
// only hash available
...
...
} else {
// neither query params nor hash available
...
...
}
From the oracle java docs for code conventions
Single line comments for if-else:
if (condition) {
/* Here is a single line comment. */
...
}
Single line very short comments for if-else:
if (a == 2) {
return TRUE; /* special case */
} else {
return isprime(a); /* works only for odd a */
}
Multi line comments for if-else:
if (condition) {
/*
* Here is a block comment.
*/
}
just to add the missing answer for the else's comment placement, which in my opinion is the best placement for code readability for the following reasons:
if the comment is put above the else it breaks the if-else continuity
if put inside it can mixes with the comment of the first statement inside the else
// match jth arc
if (j < Count)
{
// arc matched
if (arcs[j].IsBlue) List.Add(arcs[j])
}
else // all arcs were matched
{
// check if there more arcs
if (arcs[j + 1] != null) continue;
}
It looks really good if you collapse the blocks
// match jth arc
if (j < Count)|...|
else // all arcs were matched|...|
How about this style?
Using // comment for whole if-else statement description,
and /* */ comment for inner description. I use /* */ comment for not being confused with inner-comment of if-else statement.
// Process1
if (cond1-1) {
/* Process1 > Process1-1 */
Process1-1();
// Process1-1 description...
Process1-1();
Process1-1();
...
} else if (cond1-2) {
/* Process1 > Process1-2 */
// Process1-2 description...
Process1-2();
Process1-2();
Process1-2();
...
// Process1-2
if (cond1-2-1) {
/* Process1 > Process1-2 > Process1-2-1 */
Process1-2-1();
Process1-2-1();
Process1-2-1();
...
} else if (cond1-2-2) {
/* Process1 > Process1-2 > Process1-2-2 */
Process1-2-2();
// Process1-2-2 description...
Process1-2-2();
// Process1-2-2 description...
Process1-2-2();
...
} else {
/* Process1 > Process1-2 > Process1-2-else */
Process1-2-else();
Process1-2-else();
Process1-2-else();
...
}
} else {
/* Process1 > Process1-else */
Process1-else();
Process1-else();
Process1-else();
...
}
How about this? Comment right after the if keyword. Readable like natural language, leaving possibly complex condition code only for those really interested.
if /* user is logged in */ (user && user.loggedin()) {
...
} else if /* user was logged in before */ (cookies.user && sizeof(cookies.user)>0 && cookies.user.value=="foobar" && some_other_things_in_a_long_condition) {
...
} else /* apparently there's no user */ {
...
}
Related
I don't know if that forum is the right place for doing such a question but here it is:
Which one should I use for more optimization? A single for statement with an if-else statement or two for statement inside of an if-else?
For example, supposing that items is a huge list:
void doSomething(List items, boolean test)
{
for(item : items) {
if (test) {
// do A statements
} else {
// do B statements
}
}
}
And the second example:
void doSomething(List items, boolean test)
{
if (test) {
for (item : items) {
// do A statements
}
} else {
for (item : items) {
// do B statements
}
}
}
So, I know that the second example may look like a code duplication, but the point is, as we can see on the first example, the computer is going to make the same tests over and over for each item of the list, is it really a problem for optimization? Since inside the loop, the test boolean is not going to change its value at all.
I would prefer the second construct as it avoids the repetition of the test.
As claimed by others, the compiler might do the transformation. But you don't know for sure, and the cost of duplicating the loop statement isn't significant.
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 8 years ago.
Improve this question
I often write code such as the following
bool myFunct (...)
{
if (something)
{
return false;
}
// .... more code ....
}
The alternative is
bool myFunct (...)
{
if (something)
{
return false;
}
else
{
// .... more code ....
}
}
Of course, that else block is unnecessary, because the early return means that reaching the else statement in the first place is the equivalent of being inside it. Then there's the fact that, to make the compiler happy, I often have to change the structure of the 2nd implementation to
bool myFunct (...)
{
bool retval = true;
if (something)
{
retval = false;
}
else
{
// .... more code ....
}
return retval;
}
which is extra code and looks stupid. My question is, what do the governing authorities and priests say about this type of situation?
Not only it is OK, it is even encouraged in Spartan Programming. According to Spartan Programming - shorter and simpler code is better, and you achive it (among other ways) by fast terminations and avoiding else statements when possible
Under minimizing use of control:
(2) Simplifying conditionals with early return.
(4) Simplifying logic of iteration with early exits (via
return, continue and break statements).
P.S. It seems #Jeff Atwood also likes the spartan programming way
Of course. You're basically writing a guard condition that will stop you trying to perform unnecessary logic. It's fine.
Like many things, it's personal preference, but I prefer to see code written like your second example for simple cases, and the third example for more complex cases. That doesn't mean any are wrong, though.
There's nothing technically wrong with having an else clause for an if clause that does not terminate naturally (e.g., has a return or throw statement), it's just useless.
Several style guidelines argue against it (and several IDE and analysis tools may produce warnings to support these guidelines), but ultimately, it's just a preference.
The 2nd example looks fine to me because, if the code in the first statement is updated like below, it'll prevent unexpected behavior :
bool myFunct (...)
{
if (something)
{
// ... stuff
if (something_else) return false;
}
else
{
// .... more code ....
}
}
I'm getting this violation on sonarqube Nested If Depth
if (some condition){
some code;
if (some condition) {
some code;
}
}
and also here:
for (some condition) {
if (some condition) {
some code;
}
}
how can I reduce the depth?
Answer is already accepted, but doesn't answer the actual question.
So for completeness sake I want to add my 2 cents.
For reference see This question here
The example you list looks like it is dealing with guard conditions. Things like "only run this method if ...." or "only perform this loop iteration if ...."
In these cases, if you have 3 or 4 groups of guards you might end up indenting very deeply, making the code harder to read.
Anyways the way to fix this code to be more readable is to return early.
instead of
if (some condition) {
// some code
if (some other condition) {
// some more code
}
}
You can write
if (!some condition) {
return;
}
// some code
if (!some other condition) {
return;
}
// some more code
You now only every have 1 level of nesting and it is clear that you do not run this method unless 'some condition' has been met.
The same goes for the loop, using continue:
for (some condition) {
if (some other condition) {
// some code;
}
}
becomes
for (some condition) {
if (!some other condition) {
continue;
}
// some code
}
What you would state here is that unless 'some other condition' is met, you skip this loop.
The real question is why is the max depth set to 1 ? It's overkill.
This kind of rule is meant to keep your code readable. More than 2 nested blocks can make the code unreadable, but 1-2 will always be readable.
If you decide to keep the max depth set to 1, you need to refactor your code and put every 2nd condition check inside a separate method. No offense, but unless you have a very specific and good reason to do it, it looks like a bit stupid.
Which will typically have better running time, multiple if blocks or a single if/else block?
if (statement1) {
/* do something */
return result;
}
if (statement2) {
/* do something */
return result;
}
if (statement3) {
/* do something */
return result;
}
Versus:
if (statement1) {
/* do something */
return result;
} else if (statement2) {
/* do something */
return result;
} else if (statement3) {
/* do something */
return result;
}
I've always used the first style when the logical statements weren't in any way related, and the second if they were.
EDIT
To clarify why this thought popped into my head, I am programming a prime checker and have an if block that looks something like this:
if(n<2) return 0;
if(n==2) return 1;
if(n%2==0) return 0;
...
Which will typically have better running time, multiple if blocks or a single if/else block?
This is largely irrelevant as the semantics are different.
Now, if the goal is comparing the case of
if (a) { .. }
else if (b) { .. }
else { .. }
with
if (a) { return }
if (b) { return }
return
where no statements follow the conditional then they are the same and the compiler (in the case of a language like C) can optimize them equivalently.
Always go for if else if... when you know only one of the condition is to be executed, Writing multiple if's will make the compiler to check for each and every condition even when the first condition is met which will have a performance overhead, multiple if's can be used when u want to check and perform multiple operations based on certain condition
The if/else approach is faster, because it will skip evaluating the following conditions after one test succeeds.
However, the two forms are only equivalent if the conditions are mutually exclusive. If you just mindlessly convert one form into the other, you will introduce bugs. Make sure that you get the logic right.
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
Which is better, nesting an if statement inside the if block, or inside the else block?
a.
if (cond1)
if (cond2){
statement1;
statement2;
...
}
else {
statement3;
statement4;
...
}
else {
statement5;
statement6;
...
}
b.
if (!cond1) {
statement5;
statement6;
...
}
else if (cond2) {
statement1;
statement2;
...
}
else {
statement3;
statement4;
...
}
Thanks for the replies so far. I just edited the options, but my main concern really is just this: If you have a choice, (by changing the conditional expressions) is it better to nest an if statement in a higher level if's if block or its else block? (a) is just an example of nesting the if in the if block, and (b) is an example of nesting the if in the else block. Thanks again for everyone's time.
EDIT: Thanks for clarifying the question. The question is now really one of style and comes down to what is most readable. Generally speaking the latter is nicer when you have a true multi-way conditional, meaning at some point in the code there are three possible conditions all equally likely and equally sensible. The former is cleaner perhaps when semantically cond1 is the real driver, and cond2 is a kind of subordinate condition that people only think about when cond1 is true.
OLD ANSWER:
Here is one interpretation of the question ("nesting inside of then"):
if (cond1) {
if (cond2) {
A
}
} else {
B
}
This should be written, as Justin points out, as
if (cond1 && cond2) {
A
} else {
B
}
unless there is code that needs to be in the if cond1 part that is not in the scope of the if cond2.
Another interpretation of your question ("nesting inside of else") is:
if (cond1) {
A
} else {
if (cond2) {
B
}
}
In this case you should rewrite as
if (cond1) {
A
} else if (cond2) {
B
}
Because it better expresses the idea of the multiway conditional. Again if there is something that belongs in the scope of not cond1 but not in the scope of the cond2, then you need to nest.
Hope that helps.
Actually, your examples don't match. I would rewrite the first to be:
if(cond && cond2)
{
}
else
{
}
The only time I would nest if statements like your first example would be:
if(cond)
{
if(cond2)
{
// Stuff that requires both conditions to be true.
}
// Stuff that requires only the first condition to be true.
}
else
{
}
Edit: In that case, I don't think either is necessarily better. In my opinion, (b) is much easier to read and follow logically. Either one will do though!
Does the else in (a) go with the first if statement or the second? By the way you indented, I would assume that it goes with the first if statement, but if that is the case, then your two examples aren't the same logically.
Example :
<?php
if(find_user($email)){
if(check($email,$password)){
$_SESSION['email'] = $email;
setcookie("name",$_SESSION['name'],time() +40);
header("Location: index.php");
}else{
echo "incorrect email or password";
}
}else{
echo "username not found !";
}
?>
<?php
if(find_user($email)){
if(find_user($name)){
if(check($password,$passwordcp)){
$f = "readme.txt";
$file = fopen($f,"a+");
fwrite($file,"\n".$email.","$password.",".$name);
fclose($file);
}else{
echo "Password contains invalid characters";
}else{
echo "username already exist !";
}
}else{
echo "email already exist !";
}
?>