liveBook · Manning

Consumer-driven interface

As explained in Go by Example

A consumer-driven interface is an interface declared around the specific operations required by its consuming client rather than around all operations of an implementation.

A consumer-driven interface is declared by the package that uses it, around the operations that consumer actually needs. In Go, this lets an HTTP handler depend on behavior rather than a concrete storage implementation. section 10.0 section 10.4.1

This approach keeps interfaces practical:

  • Declare only essential methods, avoiding speculative or bloated contracts. section 10.4.1
  • Accept any provider whose methods satisfy the consumer’s interface; Go’s implicit interfaces require no explicit implementation declaration. section 10.4.1
  • Limit cascading changes when a provider later adds methods to its concrete type. section 10.4.1
  • Keep contracts easier to understand, test, satisfy, and compose. section 10.4.1

Handlers declare the interfaces they consume

The rest package can define one-method interfaces matching its current needs: Shortener exposes Shorten, and Resolver exposes Resolve. Its handlers accept these interfaces instead of concrete services. Both link.Shortener and sqlite.Shortener can therefore be passed to the handlers, while future storage implementations such as a cache or cloud database require no handler changes. section 10.4.2

Figure 10.6 The consumer (rest) owns the interface rather than the provider (sqlite).
A diagram of a software system

AI-generated content may be incorrect.

Diagram showing the consumer package owning the interface rather than the provider package. section 10.4.1

Declare an interface when a consumer needs one, rather than defining every possible abstraction up front. The result is a smaller contract, clearer separation of concerns, and looser coupling between handlers and implementations. section 10.4.2 section 10.4.1

How Go by Example covers it

How deep it goes
Explains interface ownership, implicit satisfaction, design benefits, and one-method handler contracts, stopping short of broader implementation mechanics.
Examples
Uses rest.Shortener and rest.Resolver with link.Shortener and sqlite.Shortener as interchangeable providers.
What it assumes
Assumes familiarity with Go packages and methods while teaching interface ownership and implicit implementation through service handlers.
What you can do after
Apply it via Go interfaces to substitute service implementations without modifying consumers.
How it connects
Connects consumer-driven interfaces with implicit interfaces, loose coupling, testability, composability, and separation of concerns.

Related concepts

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