Search code examples
javarefactoringcode-duplication

Refactoring and avoiding code duplication


I've ran into a problem that is new for me. Basically, someone else has already written a class A. The important parts looks like this

class A{

 // some instance variables

 public A(){
  // Calls methods
  build();
  // Calls more methods
 }

 private build(){
  item = makeItem();
  anotherItem = makeAnotherItem();
  // more code
 }

 private makeItem(){
  // Does some things and calls updateItem()
 }

 private updateItem(){
  // Does some things with instance variables of class A
  // and calls yet another method in class A.
 }

My problem is that build() does exactly what I need, but I need it in another class. Now here are the problems:

  1. class A does a whole lot more than the things I've written, and so I cannot create an object of it. It would be pointless.
  2. I've tried copying the build() method for my class B. However, build() uses other methods. And so I have to copy them as well and of course they call other methods and use instance variables declared in some other methods. Basically, I would have to copy 200 rows of code.

I'm guessing this problem actually has a name but I do not know what it's called and have therefore searched some basic terms only. What can I do to use build() in my class B?


Solution

  • You use the code of the build method in two classes but inheritance is not useful? Then you can reuse the code of the build method with composition. (hint Favor Composition over Inheritance) Create a new class C, which contains the build method. The class C is used by the classes A and B via composition. They delegate to the build method of the class C.

    See the refactoring method of Martin Fowler.

    https://sourcemaking.com/refactoring/smells/duplicate-code also see https://sourcemaking.com/refactoring/replace-inheritance-with-delegation