Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

double if condition, any way to make it short

I frequenty have to do something like this,

    if(condition1) {
        if {condition2) { //this condition is repeated again below
          //dosomething here 1 code 1
        }
        else{
           //dosomething here 2 code 2
        }
    }
    else {
       if {condition2) { //same if condition as above 
             //dosomething here 3 code 3
       }
       else{
             //dosomething here 4 code 4
       }
    }

Basically, only checking for if(condition2) is repeated in both case, and dosomething is different in all 4 places i.e code1, code2, code3, code4 are all different code.

So, is there anyway to make it compact and readable Or this is fine ?

Thanks.

After going through edits and looking at answers, I wonder now if this question even makes sense at all. I feel stupid now.

like image 874
newcoderintown Avatar asked Jan 11 '12 12:01

newcoderintown


2 Answers

For your specific case, the best alternative is:

NO LONGER APPLIES - valid for the case where dosomething here 1 was the same with dosomething here 3

if ( c2 )
{
}
else if ( c1 )
{
}
else
{
}

For less simple cases, you can group conditions together:

if ( c1 && c2 )
{
} 
else if ( c1 && !c2 )
{
} 
else if ( !c1 && c2 )
{
} 
else if ( !c1 && !c2 )
{
}

although I don't know if this is more readable.

If more conditions are necessary, I've seen code like this:

do {
   if (c1)
   {
      //....
      break;
   }
   if (c2)
   {
      //....
      break;
   }
   //.....
} while (false);
like image 137
Luchian Grigore Avatar answered Oct 18 '22 08:10

Luchian Grigore


NEW ANSWER AS QUESTION WAS EDITED

if ( condition1 && condition2 )
{
  //dosomething here 1 code 1
} 
else if ( condition1 && !condition2 )
{
  //dosomething here 2 code 2
} 
else if ( !condition1 && condition2 )
{
  //dosomething here 3 code 3
} 
else
{
  //dosomething here 4 code 4
}

FOLLOWING CODE IS NO LONGER VALID AS QUESTION HAS CHANGED!

I would do:

if(condition2)
{
   if(condition1)
   {
     //dosomething here
   }
   else
   {
     //dosomething here 2, 
     //which might be different than what we are doing above
   }
}

That's for your specific question, for more complex problems the solution might be different

like image 28
SERPRO Avatar answered Oct 18 '22 07:10

SERPRO