Computer Science Canada

[Tip] Smarter Conditionals

Author:  wtd [ Tue Feb 13, 2007 1:25 am ]
Post subject:  [Tip] Smarter Conditionals

Code following this pattern:

code:
if (foo) {
   if (bar) {
      baz();
   }
}


Is better written as:

code:
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.

Author:  Hikaru79 [ Tue Feb 13, 2007 1:39 am ]
Post subject:  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

Java:

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
Java:

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 Smile

Author:  BenLi [ Tue Feb 13, 2007 8:56 am ]
Post subject:  Re: [Tip] Smarter Conditionals

I disagree

if you have this
code:

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:

code:

if (foo){
   if (bar) {
      baz();
   elsif (blah){
      dostuff
   elsif (whatever){
      domorestuff
   }
}


or explain why the above is perceived to be better

Author:  rdrake [ Tue Feb 13, 2007 11:44 am ]
Post subject:  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.

Author:  wtd [ Tue Feb 13, 2007 11:49 am ]
Post subject:  Re: [Tip] Smarter Conditionals

Hikaru79 @ Tue Feb 13, 2007 2:39 pm wrote:
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

Java:

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
Java:

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 Smile


It's important to note that not all language specifications include "and" and "or" operators that short-circuit.


: