Double condition, any way to make it short

I often 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
       }
    }

In principle, only checking that (condition2) is repeated in both cases, and dosomething is different in all 4 places, i.e. code1, code2, code3, code4 are all different codes.

So, is there a way to make it compact and readable? Or is this normal?

Thank.

After going through editing and looking at the answers, I wonder if this question really makes sense. Now I feel stupid.

+5
source share
2 answers

For your particular case, the best alternative is:

NO GREAT APPLICATIONS - valid for the case when dosomething here 1 was the same with dosomething here 3

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

:

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

, .

, :

do {
   if (c1)
   {
      //....
      break;
   }
   if (c2)
   {
      //....
      break;
   }
   //.....
} while (false);
+5

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
}

, !

:

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

,

+3

All Articles