mardi 24 mars 2015

Java if statement with 2 conditions and common code

I have 2 conditions to check, if one condition is true, I need to carry out some code and if another condition is true, I need to carry out some different code. However, if either is true, I need to carry out a common piece of code in addition to the specific code.


Note only one of the 2 conditions can be true, not both.


So, I could do this in 3 ways:


Method 1



if (condition1 || condition2){

//common code here
commonCode();
moreCommonCode();

//Dig a bit deeper to see which one was true
if (condition1){

//Carry out some code here specific to condition1
specificToCondition1();
moreCondition1Stuff();

}

else {

//Carry out some code here specific to condition2
specificToCondition2();
moreCondition2Stuff();

}

}


Method 2



if (condition1){

specificToCondition1();
moreCondition1Stuff();

}

else if (condition2){
specificToCondition2();
moreCondition2Stuff();

}

if (condition1 || condition2){

commonCode();
moreCommonCode();

}


Method 3



if (condition1){

specificToCondition1();
moreCondition1Stuff();
commonCode();
moreCommonCode();

}

else if (condition2){

specificToCondition2();
moreCondition2Stuff();
commonCode();
moreCommonCode();

}


in Method 1 and Method 2, I need to check the conditions twice.


In Method 3 I have to duplicate the common code.


Am I missing something and is there a way to do this where I nether have to duplicate the code or check the conditions twice?


Aucun commentaire:

Enregistrer un commentaire