Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this a good way to reuse / share a method?

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)?

like image 935
Carlos Jaime C. De Leon Avatar asked Sep 07 '11 07:09

Carlos Jaime C. De Leon


Video Answer


1 Answers

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();
}
like image 188
Tomasz Nurkiewicz Avatar answered Oct 07 '22 18:10

Tomasz Nurkiewicz