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

I came across this code in which a call to a method like ClassA.search (a, b, flag) is 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 the code is reused? Or is there a better way to still use code reuse, but not to enter this flag to configure the code of the calling client (s) (for example, maybe split it into 3 different methods, but still be able to declare a general code refactoring method)?

+5
source share
4 answers

First, extract the comment lines using the functions:

public void search(Object a, Object b, boolean flag)
{
    commonToThree();
    if (flag)
    {
        affectTwoControllers();
    }
    else
    {
        affectsOnlyOne();
    }
    alsoCommon();
}

flag , :

public void searchWithTrueFlag(Object a, Object b) {
    commonToThree();
    affectTwoControllers();
    alsoCommon();
}

public void searchWithFalseFlag(Object a, Object b) {
    commonToThree();
    affectsOnlyOne();
    alsoCommon();
}
+6

, . , , .

, , , :

functionOne:
  sharedCodeOne()
  specificCode
  sharedCodeTwo()

functionTwo:
  sharedCodeOne()
  specificCode
  sharedCodeTwo()

, : , , /.

+3

. , , , . (, , , )

, , .

0

, :

. , , . , , ​​ , , . , .

, - ( ) , . , , .

, , java-. , , . , - , , .

( , , ), : . , , .

0

All Articles