2

We have two similar hierarchies of classes sitting in two packages. The code is not ours, so we cannot change it. We have to process these hierarchies in a certain way. So far we end up duplicating lots of code. For instance we have two methods:

void process(pckg1.Client client){...}

and

void process(pckg2.Client client){...}

The bodies of the methods are identical except for the signature. The amount of the duplication is significant, but would not probably justify complexity of reflection. Is there a better way of doing this?

Thanks, Alex

Alex
  • 93
  • 1
  • 6

1 Answers1

3

One option would be to wrap the shared methods ofpckg1.Client and pckg2.Client:

public interface ClientWrapper {
    void sharedMethod();
}

public class Packg1ClientWrapper implements ClientWrapper {
     private final pckg1.Client client;
     public Pck2ClientWrapper(final pckg1.Client client) {
         this.client = client;
     }
     public void sharedMethod() {
         client.sharedMethod();
     }
}

public class Packg2ClientWrapper implements ClientWrapper {
     private final pckg2.Client client;
     public Pck2ClientWrapper(final pckg2.Client client) {
         this.client = client;
     }
     public void sharedMethod() {
         client.sharedMethod();
     }
}

Then you can use ClientWrapper in your methods and optionally provide utility methods that create the wrapper.

public void process(final pckg1.Client client) {
    process(new Pckg1ClientWrapper(client));
}

public void process(final ClientWrapper wrapper) {
     wrapper.sharedMethod();
}

This obviously only makes sense if there are few external class and a big amount of custom code dealing with these classes.

Robin Krahl
  • 5,268
  • 19
  • 32