jeudi 6 avril 2017

Delegate objects produce duplicate code: (inheritance vs delegates)

I have ran into a situation within the OOP Java world that has stumped me while figuring out the ideal way to structure my code for "test-ability". The research that I have done has mostly pointed to delegates, which is a cool, straightforward pattern, however, I believe it results in a ton of duplicate code.

In summary, I have a class with some lengthy methods. I have a second class that 'extends' the aforementioned, lengthy class and overrides a few of said methods. The second class calls the super method while overriding the original (thus the first class is completely necessary to reducing code).

Example: The stripped down parent:

public class parentClass {

public void methodX(final int source, final int target) {
   ....
}
}

The stripped down child:

public class childClass extends parentClass {

@Override
public void methodX(final int source, final int target) {
   super.methodX(source, target)
   ... // extra logic
}
}

My thoughts and issues: Writing a test class for the childClass (class that is extending and overriding its parents methods) is incredibly difficult because we call a super method! The super method is heavily critical in avoiding duplicate test code i.e. the code to test parentClass will have to be used in childClass. I can mock a lot of these internal methods manually with Mockito, but it definitely seems like terrible practice.

My questions: Is this a fair way to use a super method or extend a class like this at all (child classes should be avoided -- composition > inheritance)? Is it necessary to test the parentClass whenever we test the child classes? What design patterns would be used to refactor the code appropriately to avoid this situation?

Aucun commentaire:

Enregistrer un commentaire