I have designed a small library for work that consists of a few exposed classes. These can basically be thought of as a server
class and client
class. But now that I am writing all the test cases and examples, I am questioning myself on whether the classes should be used in a class or inherited.
I know about the composition over inheritance theology but at the same time, the OOP basics pop into my head: has-a and is-a relationships.
My main question is which makes more sense and which would make it easier for the programmers that use my library?
I have already ready numerous topics on SO and Programmers regarding this topic, none really target my question though:
- Where does this concept of “favor composition over inheritance” come from?
- Why should I prefer composition over inheritance?
- Composition vs. Inheritance
4
In the first place, any class you do write should be inheritable/extendable. C# seems to seal all its system classes and so causes me no end of trouble. Inheritence is tricky, particularly when the superclass programmer doesn’t know what the subclass programmer will need and the subclasser can’t modify the superclass. (And in some cases cann’t even look at the superclass’s code.) But inheritance can give your end users a lot of power for very little effort on their part.
But otherwise, I’d go with composition. I frequently start with a base class, extend it in all directions, then realize the base class should be an interface. If it’s all in my code, this is no problem, but people using your library are going to be stuck with your choice. In Java I’ve ended up with two classes that look identical as far as my needs are concerned. If I could make each of them implement my own simple interface (by adding “extends myInterface”–they’ve both already got the methods) I’d be all set, but I have to treat them as distinct, unrelated classes.
The best idea might be to provide good interfaces and default implementations so the end users can do whatever they want. I guess my point is that your library’s users should be the ones to make the composition vs. inheritance decision; your job is to give them the option.
3
Programmers should favor composition over inheritance in OO languages, period. Unless your library has a compelling reason to make forced inheritance more natural/effective, then you should assume that people will consume your library via composition.
Especially as a library writer since changing a class that is being inherited will cause more failure (in general) than one that is being composed.
3