user1849060
user1849060

Reputation: 651

Alternative to long if-statement

If I have an if-statement that has its conditions constructed like this:

if((condition 1) && (condition 2) && (condition 3))

And I want to add an else-if clause where the conditions are the same but one of them (let's say the last one) is now false instead of true, is there a way of expressing this without having to resort to doing this:

if((condition 1) && (condition 2) && (condition 3))
{
  //Some code
}
else if((condition 1) && (condition 2) && !(condition 3))
{
  //Some code
}

The only way I can think of doing this is to store the result of the condition(s) that I want to be true in both cases beforehand using a variable:

$x = (condition 1) && (condition 2) ? true : false;

But is there a better alternative to this?

Upvotes: 0

Views: 476

Answers (2)

Francisco Presencia
Francisco Presencia

Reputation: 8860

You could go with

if((condition 1) && (condition 2))
  {
  if (condition 3)
    {
    //Some code
    }
  else
    {
    //Some code
    }
  }

However, I have to question the logic here. Are condition 1 and 2 required to happen? Then you could simplify it greatly by doing:

if (!(condition 1))
  throw new Exception("Condition 1 didn't happen");

if (!(condition 2))
  throw new Exception("Condition 2 didn't happen");

if (condition 3)
  {
  //Some code
  }
else
  {
  //Some code
  }

You should choose the types of Exceptions depending on your condition, or maybe not even choose to throw an exception at all. But, in this way, your code gets greatly simplified. And that should be your main objective: to fight complexity. When you start getting into several nested conditionals you start to make your code unmaintainable.

Upvotes: 0

arkascha
arkascha

Reputation: 42935

You can nest the conditions:

if ( (condition 1) && (condition 2) ) {
    if (condition 3) {
      //Some code
    } else {
      //Some other code
    }
}

Upvotes: 1

Related Questions