When developing software with multiple related classes, you’ll often notice patterns of repetition. Consider a social media application where you’re implementing different post types: TextPost, PhotoPost, and VideoPost. Without inheritance, you might find yourself repeatedly coding the same fields like author, timestamp, and likes, along with identical methods such as addComment() and like(). This duplication is a clear signal that these classes share a common conceptual parent.
In this section, we explicitly integrate the concept of class hierarchies and inheritance into the early steps of our Design Recipe, especially Steps 0 (Understand & Restate) and 1 (Data Definitions). By carefully examining and iteratively refining our initial understanding and data definitions, we identify shared structures early, thereby creating opportunities for well-designed superclasses or interfaces.
This approach directly aligns with the DRY (Don’t Repeat Yourself) principle: instead of repeating code, we consolidate shared behaviors into a single superclass. Planning for this ahead of time not only reduces redundancy but also significantly simplifies future maintenance and extension of our codebase.
Insight9.5.1.The Cost of Retrofitting Inheritance.
Adding inheritance to an existing codebase is much more challenging than designing with inheritance in mind from the start. When you realize multiple completed classes share common functionality, retrofitting a superclass requires:
Consider this scenario: you’ve already implemented several social media post classes (TextPost, PhotoPost, and VideoPost) each with identical fields for tracking authors, timestamps, and likes. Now you need to add a new feature for tagging users in any post type. Without a proper hierarchy, you’d need to duplicate this tagging functionality across all three classes. This is precisely the kind of refactoring challenge that early inheritance planning would have prevented.