1. 2
    1. 1

      One important thing I usually see missing from “composition vs inheritence” discussions: contracts. Once you think in terms of class contracts, it’s obvious when you should use one or the other. If you inherit from a class, then

      • You may not strengthen any preconditions.
      • You may not weaken any postconditions.
      • You may not weaken any class invariants.

      Do you want all of that to hold? Use inheritance. Need something else? Composition.

      1. 3

        The problem with those rules is that almost no programming languages enforces them when you use inheritance. Which means you have to rely on all the developers who interact with your codebase in any way to follow them and some of them don’t know anything about your codebase. (i.e. library authors). It’s a recipe for much sadness later down the road.

        You are much better off just not using inheritance 99.9% of the time. And the other .1% of the time you’re probably still going to cause some poor maintenance programmer a world of pain when they deal with the fallout.

        1. 3

          Eiffel, D, and Ada all do. It’s a bit more accurate to say no popular language enforces them :p

    🇬🇧 The UK geoblock is lifted, hopefully permanently.