04 / 04

Explain interface composition and give a practical backend example.

Go interfaces can embed other interfaces to build larger contracts from smaller ones, following the Interface Segregation Principle and making mocking in tests trivial.

Interface composition in a backend service
Best practices
  1. 1

    Keep interfaces small — the io.Reader/io.Writer pattern (one or two methods) is idiomatic

  2. 2

    Define interfaces in the package that uses them, not the package that implements them

  3. 3

    Compose interfaces at the point where a broader contract is genuinely needed

  4. 4

    Narrow interfaces make unit testing easy — mocks only need to implement what is used

  5. 5

    Accept interfaces, return concrete types is a common Go guideline