Comparison
Covariance and contravariancevsLiskov substitution principle
Covariance and contravariance
a list of cats would not go where a list of animals was expected, and the compiler was right even though it felt wrong.
The rules for when a generic or function type built from a subtype is itself a subtype: return positions are covariant, parameter positions are contravariant, and mutable containers are neither. It is the formal machinery behind the Liskov substitution principle and the reason a read-only sequence type can be more permissive than a mutable one. It comes up in interviews far more often than it comes up in a working day, but it comes up in a working day as a compiler error you cannot otherwise explain.
Full entry →Liskov substitution principle
the subclass threw on a method the parent promised, and every caller written against the parent was suddenly wrong.
The rule that an instance of a subtype must be usable anywhere the supertype is, without the caller having to know. Violations are easy to spot once you know the shape: a subclass that strengthens a precondition, weakens a guarantee, or throws where the parent returned. The square-and-rectangle example is the standard illustration, but the version you meet in real code is a read-only collection that inherits from a mutable one.
Full entry →