When should you use composition instead of inheritance, and what does that buy you?
You use composition instead of inheritance when the child uses the parent rather than being a special kind of it. And what it buys you is that you can swap the part at any time and nothing else has to change.
public class Main {
public static void main(String[] args) {
Notifier n = new LoggerNotifier(new ConsoleLogger());
n.notify("disk low");
}
}
And here is the composition version, where the notifier holds a logger instead of being one.
public interface Logger {
void log(String message);
}
public class ConsoleLogger implements Logger {
@Override
public void log(String message) {
System.out.println(message);
}
}
public class LoggerNotifier implements Notifier {
private final Logger logger;
public LoggerNotifier(Logger logger) {
this.logger = logger;
}
@Override
public void notify(String message) {
logger.log(message);
}
}
So what does composition buy you? Four things.
the gain why it matters
-------------------------------- --------------------------------------------
you can swap the part a different logger is a
different argument
there is no shared state each part has its own data
the class is not tied the caller depends on the
to the parent interface, not the class
you do not inherit the parent does not change when
unwanted behaviour the other part changes
And the first one is the big one. With inheritance the logger is decided inside the class and the caller has no say. With composition the caller hands it over, so the same notifier class can log to the console in one place and to a file in another.
Notifier toConsole = new LoggerNotifier(new ConsoleLogger());
Notifier toFile = new LoggerNotifier(new FileLogger("audit.log"));
And there is one more gain that is worth knowing about, and it is about the tests. With inheritance you cannot replace the part without making a subclass, which means making a class that exists only for the test. With composition you just pass a different object, and the test object can be three lines long.
And there is a fourth thing that people forget. With inheritance the child is tied to the parent for ever. If the parent changes its mind about how the state is held, then every child has to change with it. With composition the child does not know that the parent exists at all, it just calls a method on something it was given.
So the rule to remember is this. Compose when the relationship is "has a" and extend when it is "is a".
The next two questions in this topic are about the arguments for inheritance and about the fragile base class problem.