liveBook · Manning

Liskov Substitution Principle

As explained in Go in Action, Second Edition

The Liskov substitution principle states that objects of a subtype should be usable wherever objects of its supertype are expected without invalidating program correctness.

The Liskov Substitution Principle (LSP) requires every implementation of an interface to work wherever that interface is expected without breaking application correctness. In Go, interfaces make this contract explicit while keeping consumers independent of concrete implementations. section 11.1.2

Apply LSP by designing around stable interfaces and interchangeable implementations:

  • Define a Fetcher interface for retrieving and parsing feeds, allowing production readers, mocks, or future libraries to serve the same consumer. section 11.1.2
  • Define Storage for persistence, while embedding the narrower ArticleReader interface for consumers that only need read access. section 11.1.2
  • Depend on the smallest interface required: an HTTP handler accepting ArticleReader can use the full BoltStore or a test double without changing handler code. section 11.3.2

A read-only handler accepts multiple storage implementations

Define the handler around domain.ArticleReader, inject that dependency with New, and pass a concrete store or test stub. The handler relies on GetRecent and GetByID rather than BoltStore details, so production and testing implementations satisfy the same contract. section 11.3.2

How Go in Action, Second Edition covers it

How deep it goes
Explains substitution through Go interfaces, narrowed dependencies, and production-versus-test implementations, without detailing formal behavioral contracts.
Examples
Demonstrates Fetcher, Storage, ArticleReader, BoltStore, RSSReader, MockFetcher, and isolated HTTP handler tests.
What it assumes
Assumes familiarity with Go interfaces and larger-project structure while teaching interface-driven domain boundaries through concrete feed and storage examples.
What you can do after
Apply interface substitution to inject production stores, feed readers, mocks, and test doubles without changing consuming packages.
How it connects
Connects interfaces with hexagonal architecture, ports and adapters, dependency direction, and test doubles.

Also explained in

Compare how 5 books explain Liskov Substitution Principle →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go in Action, Second Edition. The section links point to the parts of the book it draws on.