
-----------------------------------
wtd
Tue Feb 13, 2007 1:25 am

[Tip] Smarter Conditionals
-----------------------------------
Code following this pattern:

if (foo) {
   if (bar) {
      baz();
   }
}

Is better written as:

if (foo && bar) {
   baz();
}

Yes, this seems horribly obvious, but it's something a lot of people do a lot more than they'd like to.

-----------------------------------
Hikaru79
Tue Feb 13, 2007 1:39 am

Re: [Tip] Smarter Conditionals
-----------------------------------
It probably happens because a lot of people aren't aware of exactly how "&&" type of statements get evaluated. For example, it is understandable for one to (mistakenly) think that


if (x!=0 && (1/x)==3)
     {
            ....
 would lead to a division-by-zero error in the case that x==0 after all. Whereas the same person would have no problem with

if (x!=0)
     if ((1/x)==3)
          {
               .....


It's important to consciously be aware of the way the first if statement is evaluated. Once we have that, the rest follows :)

-----------------------------------
BenLi
Tue Feb 13, 2007 8:56 am

Re: [Tip] Smarter Conditionals
-----------------------------------
I disagree

if you have this

if (foo && bar) { 
   baz(); 
elsif (foo && blah){
   dostuff
elsif (foo && whatever){
   domorestuff
}


wouldn't it be a better logic structure if it was more like:


if (foo){
   if (bar) { 
      baz(); 
   elsif (blah){
      dostuff
   elsif (whatever){
      domorestuff
   }
}


or explain why the above is perceived to be better

-----------------------------------
rdrake
Tue Feb 13, 2007 11:44 am

RE:[Tip] Smarter Conditionals
-----------------------------------
In the case wtd provided, it's best to condense it.  In your case BenLi, it's best to factor out that bit.

It really depends on the situation.

-----------------------------------
wtd
Tue Feb 13, 2007 11:49 am

Re: [Tip] Smarter Conditionals
-----------------------------------
It probably happens because a lot of people aren't aware of exactly how "&&" type of statements get evaluated. For example, it is understandable for one to (mistakenly) think that


if (x!=0 && (1/x)==3)
     {
            ....
 would lead to a division-by-zero error in the case that x==0 after all. Whereas the same person would have no problem with

if (x!=0)
     if ((1/x)==3)
          {
               .....


It's important to consciously be aware of the way the first if statement is evaluated. Once we have that, the rest follows :)

It's important to note that not all language specifications include "and" and "or" operators that short-circuit.
