Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it bad practice to place an if/else inside of another else?

if() {

}else {
    if (IsAlternateRow=='true')
        IsAlternateRow = 'false';
    else
        IsAlternateRow = 'true';
}

Can I place an if and else statement inside of another else statement?

like image 912
theJava Avatar asked Nov 28 '22 04:11

theJava


2 Answers

Note: the question got re-tagged as JavaScript after this answer was posted (it was originally about Java, so this answer is about Java).

In general, it is fine to place an if and an else inside an else clause.

There are, however, several issues with your code. IsAlternateRow=='true' isn't syntactically valid.

  • If it's a string comparison, you should use double quotes and .equals();
  • If it's a boolean comparison, you're better off simply doing IsAlternateRow = !IsAlternateRow instead of the entire nested if.
like image 200
NPE Avatar answered Dec 09 '22 17:12

NPE


Yes, placing an if inside an else is perfectly acceptable practice but in most cases use of else if is clearer and cleaner. E.g.

if (test) {
   // Do something
} else if (otherTest) {
   // Do something else
} else {
   // Do a third thing
}

infact this is short-hand for

if (test) {
   // Do something
} else {
     if (otherTest) {
         // Do something else
     } else {
         // Do a third thing
     }
}

and the two should compile to almost identical programs in most situations.

Your code example is not very clear and will not compile correctly, clearer sample code may help us to help you out.

like image 44
Ben Page Avatar answered Dec 09 '22 17:12

Ben Page