66

Replace Superclass with Delegate


Goal

Inheritance from a superclass that doesn't really fit (Liskov violations, awkward methods) becomes composition: the former subclass holds an instance and delegates explicitly.

Before the refactoring
class CategoryItem extends Scroll {
  // uses some Scroll methods, refuses others
}
After the refactoring
class CategoryItem {
  constructor() { this.scroll = new Scroll(); }
  date() { return this.scroll.date(); }
}
Savings

The misleading is-a relationship disappears; the former subclass can change its delegate's class without affecting its callers.

Note

Adds a forwarding method on the former subclass for every method the old superclass exposed — only worth it when the superclass relationship is misleading.