Friday, June 24, 2016

You want the code clearer? Add useless conditionals

Imagine this situation:

You have a shopping cart and after a product is ordered, its status can be ApprovedDeclined or Not Available.

If the product is not available, you want to do some processing and then display a message depending if it is declined or not available.

The code looks like this:


 if ([product isNotAvalable] || [product isDeclined]) {
  //some common functionality

  if ([product isNotAvalable]) {                    
    //do something
  } else {
    //do something else
  }
}

Nothing wrong with this code. For the second if, it is obvious that "do something else" is happening when the product is declined.

What if a developer looks only to this piece of code:

  if ([product isNotAvalable]) {                    
    //do something
  } else {
    //do something else
  }

There is a big chance that he will understand that "do something else" is happening when the product is not "not available" that is when the product is available, that is Approved.

To prevent this, we can add a useless conditional like the following:

 if ([product isNotAvalable] || [product isDeclined]) {
  //some common functionality

  if ([product isNotAvalable]) {                    
    //do something
  } else if ([product isDeclined]) {
    //do something else
  }
}

Useless? True!

But very useful ;)


(Image credit)

No comments:

Post a Comment