Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Would you happen to know any good literature with clear composition examples vs inheritance?

The C++ and Python code I see daily is fully inheritance focused, and I would like to understand how it could be done differently (or better) starting from a perspective I understand.




Got a simpler example?


Well in my game everything inherits from GameObject. GameObject has a draw method. Enemies, coins, the player, doors, they're all GameObjects. But when it comes to drawing things, the logic doesn't vary by those subtypes. Rather some things are pixel art with a collection of frame by frame animations. Other things are just a static image. Some things I render as text. Some things are really complex, I render them as composable components with different frames of animation/keyframes, created in a custom character editor program. Each of those render modes I described is a different DrawObject. So instead of having an insanely complex inheritance hierarchy of all permutations of things and how they are drawn (or trying multiple inheritance), I have GameObjects and they contain an property/object of type DrawObject. I have a shallow inheritance hierarchy of GameObjects and a shallow inheritance hierarchy of DrawObjects. And I can compose them together as I see fit.

I even have an AggregateDrawObject class for cases where I need to run two animations at once for a single object.

You can do something similar with UpdateObjects too and have composable behavior.

Note that I still use inheritance, but just don't let it get out of control. Anyone saying "inheritance is bad" is either a moron or really means "deep inheritance hierarchies are bad" or maybe "bad designs are bad".




Consider applying for YC's Winter 2026 batch! Applications are open till Nov 10

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: