2 ms·
No, you're right. "Favor composition over inheritance" has been the go-to OOP design advice for years. The distinguishing feature of OO is modeling concepts by
by jdlshore 13y ago
No, you're right. "Favor composition over inheritance" has been the go-to OOP design advice for years.
The distinguishing feature of OO is modeling concepts by encapsulating state and behavior. For some reason, introductions tend to focus on complex inheritance structures instead. I think that's really unfortunate because it sends entirely the wrong message about OOP.
That said, I do occasionally use inheritance for polymorphism and limited code reuse (such as [1]), but I keep it limited in scope, and I don't think I've ever used a multi-level inheritance hierarchy.
[1] In my Let's Play TDD screencast series, I use inheritance when modeling a "Dollars" value object. There's a Dollars base class and then various specializations: ValidDollars, InvalidDollars, and UserEnteredDollars.
Source code: https://github.com/jamesshore/lets_play_tdd/tree/master/src/com/jamesshore/finances/values https://github.com/jamesshore/lets_play_tdd/tree/master/src/...
The screencast: http://www.jamesshore.com/Blog/Lets-Play/ http://www.jamesshore.com/Blog/Lets-Play/