Hacker News new | ask | show | jobs
by catnaroek 3686 days ago
Inheritance isn't the same thing as subtyping:

(0) Inheritance is a (rather undisciplined) form of code reuse - it's literally automation for copying and pasting part of an existing definition into the body of another. It doesn't presuppose a notion of type.

(1) Subtyping is a semantic relationship between two types: all terms of a subtype also inhabit its supertype(s).

There's nothing too wrong with inheritance as long as you're aware that it doesn't always lead to the creation of subtypes. This is, for example, the case in OCaml.

Sadly, Java, C# and C++ confuse matters by conflating classes with types (which is tolerable) and subclasses with subtypes (which is a logical absurdity and leads to painful workarounds, I mean, design patterns, as we all have learnt the hard way).

1 comments

The Java style (Nominal) subtyping is what most people are familiar with, and the most common reason why people think subtyping is necessary, so let's not stray into other kinds of subtyping until we can agree on this kind.
I never said subtyping isn't necessary, and if you read my reply to btilly, you'd see that I actually suggested otherwise: subtyping is basic, natural and necessary, so languages should do it right.

Also, as I again previously said, nominal typing and even nominal subtyping are fine (well, I said “tolerable”, since they have downsides for modularity, but that's a topic for another day), but conflating inheritance with subtyping is a problem. To put it in Java terms, a subclass should only be considered a subtype if:

(0) The subclass doesn't override any methods that aren't abstract in the superclass. A subclass can do whatever its implementor wishes, but a subtype can't behave differently from a supertype.

(1) The subclass doesn't directly mutate any inherited fields from the superclass - this destroys inherited invariants. OTOH, reading inherited fields is just fine in a subtype.

In other words, a subclass is a subtype if and only if the type-checker has enough information to tell that the Liskov substitution principle actually holds.