SOLID & Design Patterns Interview Question #139

How does Liskov Substitution influence inheritance design?

Anti-Patterns, Refactoring, DI Lifetimes & Senior Design Scenarios Senior Advanced

Quick Interview Answer

Liskov Substitution requires that code using a base abstraction continue to behave correctly when a subtype is supplied. A subtype should preserve the expectations, invariants, and meaningful behavior of the base contract.

Detailed Explanation

Liskov Substitution requires that code using a base abstraction continue to behave correctly when a subtype is supplied. A subtype should preserve the expectations, invariants, and meaningful behavior of the base contract.

If a subclass must throw NotSupportedException for normal base operations or substantially changes their meaning, the hierarchy may be modeling the relationship incorrectly.

Code Example

public interface IReadableFile
{
    string Read();
}

public interface IWritableFile : IReadableFile
{
    void Write(string text);
}

// A read-only file need not pretend
// that Write is supported.