Object inheritance

Topics: Object-oriented programming

Inheritance lets related classes share behaviour while subclasses specialize it.

Subtopics

Inheritance for sharing behaviour

“Inheritance solves the problem of related types that share a great deal of common behavior but differ across some dimension. It allows you to isolate shared code and implement common algorithms in an abstract class, while also providing a structure that permits subclasses to contribute specializations.”
—Sandi Metz, Practical Object-Oriented Design in Ruby - Sandi Metz

Abstract base classes

When many classes share code, extract an abstract superclass.

“The best way to create an abstract superclass is by pushing code up from concrete subclasses. Identifying the correct abstraction is easiest if you have access to at least three existing concrete classes.”
—Sandi Metz, Practical Object-Oriented Design in Ruby - Sandi Metz

Abstract base classes need to implement template methods to document the “interface definition”. They do so by throwing an error message if the method has no concrete implementation in the child class.

“Always document template method requirements by implementing matching methods that raise useful errors.”
—Sandi Metz, Practical Object-Oriented Design in Ruby - Sandi Metz

Instead of requiring these implementations to call super to add the missing pieces of an algorithm, implement the algorithm fully in the base class using empty hook methods that get implemented by the child class.

“Instead of allowing subclasses to know the algorithm and requiring that they send super, superclasses can instead send hook messages, ones that exist solely to provide subclasses a place to contribute information by implementing matching methods. This strategy removes knowledge of the algorithm from the subclass and returns control to the superclass.”
—Sandi Metz, Practical Object-Oriented Design in Ruby - Sandi Metz

Bookmarks

Questions