class may inherit […] the fields and methods of its superclass. Inheritance is transitive […]. Subclasses may override some methods and/or fields to alter the default behavior. ▸ Composition: when a Field’s type is a class, the field will hold a reference to another object, thus creating an association relationship between them. Steven Lowe - Composition vs. Inheritance: How to Choose?
GET THE IDEA THAT INHERITANCE SHOULD BE USED EVERYWHERE. THIS CAN RESULT IN AWKWARD AND OVERLY COMPLICATED DESIGNS. INSTEAD, YOU SHOULD FIRST LOOK TO COMPOSITION WHEN CREATING NEW CLASSES, SINCE IT IS SIMPLER AND MORE FLEXIBLE.” (Bruce Eckel - Thinking In Java, 1998) “FAVORING OBJECT COMPOSITION OVER CLASS INHERITANCE HELPS YOU KEEP EACH CLASS ENCAPSULATED AND FOCUSED ON ONE TASK. YOUR CLASSES AND CLASS HIERARCHIES WILL REMAIN SMALL AND WILL BE LESS LIKELY TO GROW INTO UNMANAGEABLE MONSTERS. “ (Gamma et al - Design Patterns, 1994)
A BASE TYPE TO REPRESENT THE CORE OF YOUR IDEAS ABOUT SOME OBJECTS IN YOUR SYSTEM. FROM THE BASE TYPE, YOU DERIVE OTHER TYPES TO EXPRESS THE DIFFERENT WAYS THAT THIS CORE CAN BE REALIZED.“ BUT THEN… (continues for 8 pages)
Johansson - Composition over Inheritance “Our customers demand a MurderRobotDog. It needs to be able to .kill(), .drive(), .bark(), but it cannot poop().
Johansson - Composition over Inheritance Dog meow() Cat poop() Animal clean() CleanerRobot kill() MurderRobot drive() Robot bark() GameObject MurderRobot Dog
Johansson - Composition over Inheritance bark() Dog meow() Cat poop() Animal clean() CleanerRobot kill() MurderRobot drive() Robot bark() MurderRobot Dog
Domain in terms of semantics (focus on “what it is”) ▸ Composition allows the Domain to be flexible in terms of behaviors (focus on “what it does”) ▸ Inheritance is good for fixed, well-specified hierarchies (UI), but forces design early on ▸ Composition helps with “the same, but different” (business reqs.) and allows for supple design ▸ Inheritance is easy to (involuntarily) abuse, mixing different concerns and coupling unrelated behaviors, becoming harder to reason about (and test) ▸ Composition is more explicit and, focusing on small and single-responsibility objects, remains easier to reason about (and test) (So yeah, not many tradeoffs: composition is almost always preferable)