Why seal a class?

Classes should either be designed for inheritance or prohibit it. There is a cost to designing for inheritance:

  • It can pin down your implementation (you have to declare which methods are going to call which other methods, in case a user overrides one but not the other)
  • It reveals your implementation rather than just the effects
  • It means you have to think of more possibilities when designing
  • Things like Equals are hard to design in an inheritance tree
  • It requires more documentation
  • An immutable type which is subclassed may become mutable (ick)

Item 17 of Effective Java goes into more details on this – regardless of the fact that it’s written in the context of Java, the advice applies to .NET as well.

Personally I wish classes were sealed by default in .NET.

Leave a Comment