If 2 classes have the following in common:
- part of how their state is represented (both have a linear container)
- multiple identical methods (identical code, not just signature)
But are not substitutable, ie: they play different roles.
Then how do I avoid repeating those methods?
The obvious solution would be inheritance, but I have read: “inheritance is not for code reuse”. (Does this apply here?, Is this really a case of just code reuse?)
I am deliberately not telling you which language, because I am hoping for a language agnostic answer.
The methods are couple lines long, all of them modify the container, one of them transforms/extracts a sort of “final result” from the container. By roles I mean: substituting one for the other would be valid runnable code (in the places where only the common methods are used), but would result in logic/semantic error. By inheritance I meant that introducing a 3rd class as base/super with the common methods, but that would be virtual. So by substitution I meant substituting a “sibling” type and not a subtype.
8
Sometimes, inheritance can be used for code re-use. Especially private inheritance in languages that support it.
And if that is not possible for you, you can always factor out the common stuff into a separate class and use composition to include it in your original classes.
In any case, before you refactor this, you should consider if the similarity is structural or accidental. Ask yourself these questions:
- Do the container and associated functions represent the same concept in both places where they are used?
- Is it possible the container type gets changed in one place without it having to be changed in the other? Same goes for the implementation of the functions.
If the answer to the first is ‘No’ or to the second is ‘Yes’, then the similarity is accidental. Thus you are not repeating yourself and don’t need to refactor.
1