AlgoViz

Liskov substitution (LSP)

medium 55 min

An object of a subtype must be usable wherever the supertype is expected, with no surprise for the caller.

Watch lesson5:06

Where it shows up

The same pattern appears across everyday software.

  • Java: Stack and Vector

    `java.util.Stack` extends `Vector`, so every stack also has `insertElementAt`. The documentation says that a more complete and consistent set of stack operations is provided by `Deque`, which should be used in preference.

  • Java: Properties and Hashtable

    `Properties` is a table of strings but inherits `put(Object, Object)`. The documentation strongly discourages it, and calls an object that contains other things compromised: `store` and `save` then fail.

  • Java: optional operations

    Mutator methods of `Collection` may be specified to throw UnsupportedOperationException. `List.of` uses this: every mutator throws. The contract is kept by the letter, and callers must know.

  • Java: IdentityHashMap

    Its documentation says that it implements `Map` but intentionally violates the general contract of `Map`, because it compares keys by reference. A rare case of a violation declared in public.

  • java.sql.Timestamp

    Extends `java.util.Date`. Its documentation says that `equals` is not symmetric with that of Date, and recommends that code does not view Timestamp values generically as Date.

  • Java arrays

    Arrays are covariant, so a `String[]` can be held as `Object[]`. The documentation of ArrayStoreException shows the result: storing an Integer fails at run time.

  • .NET Stream

    `Stream` has `CanRead`, `CanWrite` and `CanSeek`. If a derived class does not support seeking, calls such as `Seek` may throw NotSupportedException. Callers ask before they call.

  • Python io

    Streams have `readable()`, `writable()` and `seekable()`. If `writable()` is False, `write()` raises OSError, and `io.UnsupportedOperation` inherits from both OSError and ValueError so that old handlers still work.

  • Go io.Writer

    A tiny interface with a long contract in its comment: a short write must return an error, the data may not be modified, not even temporarily, and implementations must not retain it. Thousands of writers are interchangeable because of these sentences.

  • mypy

    Refuses an override with a narrower parameter or a wider result, and says that it violates the Liskov substitution principle. It sees signatures, never behaviour.