I encountered this code wherein a method call, for example ClassA.search(a, b, flag) is being used by 3 Controllers. This is a simplified version of the method:
public List<Result> search(Object a, Object b, boolean flag) {
//do some code logic here, common to the 3 controllers
//at the middle there is:
if (flag) {
//code that affects 2 Controllers
} else {
//code affects only 1
}
//some more common code
//some more code with the flag if else
}
Is this a good idea because code is reused? Or is there a better way to still be able to make code reuse but not introduce this flag for method caller (client) code customization (like maybe split it to 3 different methods but still be able to declare a common code refactored method)?
First, extract commented lines with functions:
public void search(Object a, Object b, boolean flag)
{
commonToThree();
if (flag)
{
affectTwoControllers();
}
else
{
affectsOnlyOne();
}
alsoCommon();
}
Now get rid of flag
boolean argument, which is a code smell:
public void searchWithTrueFlag(Object a, Object b) {
commonToThree();
affectTwoControllers();
alsoCommon();
}
public void searchWithFalseFlag(Object a, Object b) {
commonToThree();
affectsOnlyOne();
alsoCommon();
}
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