Recently I found a good answer to my question in Uncle Bob's "Clean Code", which I want to share. He differentiates three types of duplication
Pieces of identical code should be replaced with a single method. So the fix would be to extract the method and delegate to common behaviour.
- in the same method, perform Extract Local Variable and reuse it.
- in the same class perform the Extract Method refactoring.
- in classes of the same hierarchy Extract Method and Pull it Up. A hierarchy might be created to find a place for the methods.
- in classes of separate hierarchies use delegation to new objects.
- If the methods do not need any enclosing state, then the "lib" pattern might be applied (that is a container for static methods, usually called
if/else that always test for the same set of conditions.
- These should be replaced with polymorphism.
Modules that implement similar algorithms. These are hardest to find, as no clone detector can find them.
- As the scope is larger design patters are used. Template Method design pattern might be applied for algorithms inside a class hierarchy.
- Strategy design pattern might be applied for any algorithm that is used in different places.
Also a valid point mentioned by Oded, when dealing with different versions of libraries
- consolidate on a single version. Facade design pattern might help here.
In the end the best one sentence to answer my question is by stimms:
code reuse method used in OO languages is objects.