Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove duplicate code in java

class A extends ApiClass
{
   public void duplicateMethod()
   {
   }
}    


class B extends AnotherApiClass
{
   public void duplicateMethod()
   {
   }
}

I have two classes which extend different api classes. The two class has some duplicate methods(same method repeated in both class) and how to remove this duplication?

Edit

Both ApiClass and AnotherApiClass are not under my control

like image 573
Anantha Kumaran Avatar asked May 22 '26 21:05

Anantha Kumaran


2 Answers

Depending on what the code is you could do something like:

public class Util
{
    public static void duplicateMethod()
    {
        // code goes here
    }
}

and then just have the other two duplicateMethods call that one. So the code would not be duplicated, but the method name and the call to the Util.duplicateMethod would be.

If the code in the Util.duplicateMethod needed to access instance/class variables of the A and B class it wouldn't work out so nicely, but it could potentially be done (let me know if you need that).

EDIT (based on comment):

With instance variables it gets less pretty... but can be done. Something like:

interface X
{
    int getVar();
    void setVar(A a);
}

class A 
    extends    ApiClass
    implements X
{
}

class B
    extends    AnotherApiClass
    implements X
{
}

class Util
{
    public static void duplicateMethod(X x)
    {
       int val = x.getVal();
       x.setVal(val + 1);
    }
}

So, for each variable you need to access you would make a method for get (and set if needed). I don't like this way since it make the get/set methods public which may mean you are making things available that you don't want to be available. An alternative would be to do something with reflection, but I'd like that even less :-)

like image 111
TofuBeer Avatar answered May 24 '26 09:05

TofuBeer


Sounds like a case for the "Strategy Pattern".

class A extends ApiClass {
   private ClassContainingDupMethod strategy;
}

class N extends AnotherApiClass {
   private ClassContainingDupMethod strategy;

   public methodCallingDupMethod(){
      strategy.dupMethod();
   }
}

class ClassContainingDupMethod{
   public dupMethod(){;}
}

Or is the dupMethod inherted from the Api classes?

like image 41
lajuette Avatar answered May 24 '26 09:05

lajuette



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!