mercredi 18 août 2021

Nested if statements vs extra else if?

I come across a lot of logic work where I'm not sure what design pattern is better for if statements. In these situations, I can usually put in a nested if statement, or alternatively. These two cases are shown below. What are the pros and cons of both, is there a standard I should follow?

if (val > 0 && is_on)
{
  // (1)
}
else if (val > 0)
{
  // (2)
} 
else
{
  // (3)
}
if (val > 0)
{
  if(is_on)
  {
    // same as (1)
  }
  else
  {
    // same as (2)
  }
}
else
{
  // same as (3)
} 

Aucun commentaire:

Enregistrer un commentaire