I started out with the following, simple routine:
void originalCode(){
boolean status = getStatus();
function2(status);
if(status){
return;
}
function3();
}
But then, additional functionality required calling function1
on the status == true
path. It was also important to call function1
before function2
.
The results were one of the two following monstrosities:
void alternative1(){
boolean status = getStatus();
if(status){
function1();
}
function2(status);
if(status){
return;
}
function3();
}
or,
void alternative2(){
boolean status = getStatus();
if(status){
function1();
function2(status);
return;
}
function2(status);
function3();
}
Both have code duplication, and in general, don't look right.
Now, in my particular case, function3
isn't required to be called after function2
, so I settled on the following:
void niceAlternative(){
boolean status = getStatus();
if(status){
function1();
}else{
function3();
}
function2(status);
}
But what if that was not an option--i.e. if function2
had to be called before function3
? And in general, how do you structure code with multiple execution paths that have commonality in the middle?