Comment by saghm

5 days ago

Even before I got to the point where I decided I didn't like inheritance, I distinctly recall having conversations about how I felt that using inheritance for anything other than polymorphism didn't usually end up with particularly clean code. I can remember a conversation about this at least as far back as the summer after my freshman year of college, and I don't think I was aware of the idea of "composition" yet, because I remember phrasing my point as something like "inheritance shouldn't be used for 'code-sharing', only for polymorphism".

Out of curiosity, when you say you don't like inheritance, does that mean you never use it at all, or you only use it rarely?

Because even though inheritance often is used in a wrong way, there are definitely cases, where it is the clearest pattern in my opinion.

Like graphic libary things. E.g. everything on the screen is a DisplayObject. Simple Textfields and Images inherit directly from DisplayObject. Layoutcontainers inherit from DisplayObjectContainer which inherits from DisplayObject.

Inheritance here makes a lot of sense to me and I don't see how it could be expressed in a different way without loosing that clarity.

  • > I don't see how it could be expressed in a different way without loosing that clarity.

    What value does the inheritance provide here?

    Can't you just use a flat interface per usecase without inheritance and it will work simpler with less mental overhead keeping the hierarchy in mind?

    Explicitly your graphic library sounds should be fine to have the interface DisplayObject which you can then add default implementations on. (That's a form of composition)

    • That would be way, way more verbose for everything.

      Every display object has a x y width and height for example. And there is basic validating for every object. Now a validate method can be conposited. But variables? Also the validating, there is some base validating every object share (called wih super) and the specific validating (or rendering) is done down in the subclasses.

      And even for simple things, you can composite a extra object, but then you cannot do a.x = b.x * 2 anymore, but would have to do a.po.x = b.po.x * 2 etc

      5 replies →