nesting if statements [closed] - coding-style

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 !";
}
?>

Related

Is it ever okay to not use an ELSE statement if you have a return or throw inside the IF statement? [closed]

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 ....
}
}

SonarQube - Nested If Depth

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.

Multiple if blocks or single if/else block?

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.

Flatten conditional as a refactoring

Consider:
if (something) {
// Code...
}
With CodeRush installed it recommended doing:
if (!something) {
return;
}
// Code...
Could someone explain how this is better? Surely there is no benefit what so ever.
Isolated, as you've presented it - no benefit. But mark4o is right on: it's less nesting, which becomes very clear if you look at even, say a 4-level nesting:
public void foo() {
if (a)
if (b)
if (c)
if (d)
doSomething();
}
versus
public void foo() {
if (!a)
return;
if (!b)
return;
if (!c)
return;
if (!d)
return;
doSomething();
}
early returns like this improve readability.
In some cases, it's cleaner to validate all of your inputs at the beginning of a method and just bail out if anything is not correct. You can have a series of single-level if checks that check successively more and more specific things until you're confident that your inputs are good. The rest of the method will then be much easier to write, and will tend to have fewer nested conditionals.
One less level of nesting.
This is a conventional refactoring meant for maintainability. See:
http://www.refactoring.com/catalog/replaceNestedConditionalWithGuardClauses.html
With one condition, it's not a big improvement. But it follows the "fail fast" principle, and you really start to notice the benefit when you have lots of conditions. If you grew up on "structured programming", which typically recommends functions have single exit points, it may seem unnatural, but if you've ever tried to debug code that has three levels or more of nested conditionals, you'll start to appreciate it.
It can be used to make the code more readable (by way of less nesting). See here for a good example, and here for a good discussion of the merits.
That sort of pattern is commonly used to replace:
void SomeMethod()
{
if (condition_1)
{
if (condition_2)
{
if (condition_3)
{
// code
}
}
}
}
With:
void SomeMethod()
{
if (!condition_1) { return; }
if (!condition_2) { return; }
if (!condition_3) { return; }
// code
}
Which is much easier on the eyes.
I don't think CodeRush is recommending it --- rather just offering it as an option.
IMO, it depends on if something or !something is the exceptional case. If there is a significant amount of code if something happens, then using the !something conditional makes more sense for legibility and potential nesting reduction.
Well, look at it this way (I'll use php as an example):
You fill a form and go to this page: validate.php
example 1:
<?php
if (valid_data($_POST['username'])) {
if (valid_data($_POST['password'])) {
login();
} else {
die();
}
} else {
die();
}
?>
vs
<?php
if (!valid_data($_POST['username'])) {
die();
}
if (!valid_data($_POST['password'])) {
die();
}
login();
?>
Which one is better and easier to maintain? Remember this is just validating two things. Imagine this for a register page or something else.
I remember very clearly losing marks on a piece of college work because I had gone with the
if (!something) {
return;
}
// Code...
format. My lecturer pontificated that it was bad practice to have more than one exit point in a function. I thought that was nuts and 20+ years of computer programming later, I still do.
To be fair, he lived in an era where the lingua franca was C and functions were often pages long and full of nested conditionals making it difficult to track what was going on.
Then and now, however, simplicity is king: Keeping functions small and commenting them well is the best way to make things readable and maintainable.

Where to put comments in an if-then-else construct? [closed]

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 */ {
...
}

Resources