views:

283

answers:

5
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

A: 
class BaseApiClass
{
   public void duplicateMethod()
   {
   }
}

class ApiClass  extends BaseApiClass
{
}
class AnotherApiClass  extends BaseApiClass
{
}

class A extends ApiClass
{
}    

class B extends AnotherApiClass
{
}
antony
+1  A: 

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

TofuBeer
yes the method needs to access the instance variables
Anantha Kumaran
+1  A: 

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?

lajuette
A: 

Duplicate methods that rely on member variables imply duplicate member variables, too - and that starts to smell like too-large classes. What would those specific member variables, with the method(s), look like, if you were to extract them into their own class, and then compose that class into your other classes? Prefer composition over inheritance.

Carl Manaster
A: 

You need to combine the classes into one object and then all classes using th other two classes, modify their code to use the single class.