Video in progress
Where does the advice "favor composition over inheritance" come from?
Inheritance tightly binds the child class to the internal details of the parent and makes later changes harder. Composition relies only on the public interface, which makes swapping components and testing easier. The advice spread from the "Design Patterns" (GoF) book and Effective Java.
📖 Answer
The famous example is extending HashSet to count the added elements:
class CountingSet<E> extends HashSet<E> {
int added = 0;
@Override public boolean add(E e) { added++; return super.add(e); }
@Override public boolean addAll(Collection<? extends E> c) {
added += c.size();
return super.addAll(c); // calls add() internally!
}
}
After addAll(List.of("a","b","c")), added == 6, because HashSet.addAll calls add internally. That is an undocumented detail of the parent class, and you have become dependent on it.
With composition:
class CountingSet<E> {
private final Set<E> inner = new HashSet<>();
private int added = 0;
boolean add(E e) { added++; return inner.add(e); }
boolean addAll(Collection<? extends E> c) {
added += c.size(); return inner.addAll(c);
}
}
Now what happens inside inner doesn't affect you.
This doesn't mean "never use inheritance". If it is a real "is-a" and the parent class was designed for extension (for example, an abstract class whose documentation says "override this method"), inheritance is fine.
Sign up to mark studied questions and save your progress.