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.
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);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With