Video in progress

Strong Middle 🧱 OOP and SOLID

What is the fragile base class problem, and how does it show up in production?

A harmless-looking internal change in a parent class breaks the classes that inherit from it, because the child classes have come to depend on how the parent's methods call each other. It happens especially when a library version is updated.

📖 Answer

Say there is a class like this in an internal library:

public class BaseRepository<T> {
    public void save(T e) { ... }
    public void saveAll(List<T> list) {
        for (T e : list) save(e);   // v1
    }
}

Another team inherited from it for auditing:

class AuditedRepository<T> extends BaseRepository<T> {
    @Override public void save(T e) { audit(e); super.save(e); }
}

Even when saving through saveAll, the audit gets written, because in v1 saveAll calls save. In v2, the library rewrote saveAll as a batch insert for speed, and now save is no longer called. There is no compile error, and the tests pass too (if the saveAll audit wasn't tested). In production, the audit log stays empty.

Why this problem is dangerous:

  • the author of the parent class doesn't know who inherited where;
  • the change doesn't break the public API, only the "self-use" order;
  • the failure is silent: no exception, just wrong data.

What to do:

  • in classes open for inheritance, document which method calls which (the JDK does this in AbstractCollection: "This implementation iterates over...");
  • make classes not designed for inheritance final;
  • provide a clear extension point: a hook like protected void afterSave(T e) {};
  • for outside code, use composition or a decorator: let AuditedRepository wrap BaseRepository.