Skip to content
Tutorials Center
My learning

Topics

Lesson 54 of 147 ยท Interfaces

Designing with Interfaces

Learn how to design with Go interfaces - keep them small, define them where they are used, test with hand-written fakes, inject dependencies without frameworks and avoid interface pollution.

Knowing how interfaces work is one thing. Knowing when and where to use them is what separates code that is pleasant to change from code that fights you. Go developers follow a handful of well-worn guidelines: keep interfaces small, define them in the package that uses them, accept interfaces but return concrete types, and do not create an interface until you have a reason to.

These guidelines come from how Go interfaces work. They are satisfied implicitly, so the package that defines a type does not need to know any interface exists. That frees the consumer to describe exactly what it needs. This lesson shows the guidelines in action with a small notification service, then uses the same design to write tests with hand-made fakes and to wire a program together without a dependency-injection framework.

Keep interfaces small

The most useful interfaces in the standard library have one or two methods: io.Reader, io.Writer, fmt.Stringer, error, http.Handler. A small interface is easy to implement, easy to fake and easy to compose. Rob Pike's proverb sums it up: the bigger the interface, the weaker the abstraction.

Compare these two designs for code that needs to save a user:

Go
// Too big: every implementation must provide everything,
// and every test double must fake seven methods.
type UserStore interface {
	Get(id int) (User, error)
	List() ([]User, error)
	Create(u User) error
	Update(u User) error
	Delete(id int) error
	Count() (int, error)
	Close() error
}

// Better: each function asks only for what it uses.
type UserGetter interface {
	Get(id int) (User, error)
}

type UserSaver interface {
	Save(u User) error
}

A function that only reads a user should accept UserGetter. Its signature then documents that it cannot delete or update anything, and any type with a matching Get method qualifies, including a one-line fake in a test. When a function needs several capabilities, embed small interfaces to describe the combination.

Define interfaces where they are used

In many languages you declare an interface next to the class that implements it. In Go, the better habit is the opposite: the consumer declares the interface it needs, in its own package, listing only the methods it actually calls. The concrete type, living in another package, does not import or mention it.

Go The consumer owns the interface

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

EmailSender satisfies Notifier without any declaration tying them together. If tomorrow you add an SMS sender or a push-notification service, SignupService does not change. And because Notifier lives with its only user, it can have exactly the shape the service wants (for instance, a single Notify method even if the email client has twenty).

Defining an interface before you have two implementations or a concrete need (a test double counts) is usually premature. In Go it costs almost nothing to add one later, because no existing type has to be changed.

Accept interfaces, return structs

You will often hear the advice "accept interfaces, return structs". It means:

  • Parameters: ask for the smallest interface that does the job, so callers can pass many kinds of values.
  • Results: return the concrete type. Callers get every method and field, the code is easier to follow, and you can add methods later without breaking anyone. If you return an interface, you have to guess the future needs of every caller.
Go Why return the concrete type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The caller decides how abstract to be: a *Formal converts to Greeter implicitly whenever that is useful. The reverse (recovering Initials from a Greeter) needs a type assertion. There are legitimate exceptions, such as a factory that returns one of several implementations, or error, but they are exceptions.

Testing with hand-written fakes

Small consumer-defined interfaces make tests simple. You do not need a mocking library: write a tiny type that records what happened. Here the SignupService is tested with a fake notifier that captures messages, and with another that fails on demand:

Go Fakes without a mocking framework

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

In a real project these checks live in a _test.go file and use the testing package, the topic of the testing chapter later in the course. The shape is identical:

Go
func TestRegisterSendsWelcome(t *testing.T) {
	fake := &fakeNotifier{}
	svc := &SignupService{notifier: fake}

	if err := svc.Register("[email protected]"); err != nil {
		t.Fatalf("Register: %v", err)
	}
	if len(fake.sent) != 1 {
		t.Errorf("sent %d messages, want 1", len(fake.sent))
	}
}

Hand-written fakes are explicit and refactor-friendly: they compile against the interface, so changing the interface shows you every fake that needs updating. Reach for a generated mock only when interactions are complicated enough to justify it.

A function can implement an interface too

For a one-method interface, a function type with a method of the same name makes a convenient adapter. This is exactly how http.HandlerFunc works, and it makes quick fakes one line long:

Go Adapting a function to an interface

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Code that calls time.Now() directly is hard to test, because the result changes every run. Injecting a Clock makes behavior deterministic: the test controls time. Production code passes ClockFunc(time.Now).

Dependency injection without a framework

Many languages need a dependency-injection container. In Go, plain constructors do the job: each component receives its dependencies as arguments, usually as small interfaces, and main wires everything together. Nothing is hidden, and the compiler checks the wiring.

Go Wiring a program by hand in main

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

main is the composition root: the one place where concrete types are chosen. Swap memRepo for a database-backed type and ProfileService is untouched. Swap prefixLogger for a no-op logger in tests and the output disappears. If constructors grow long, group configuration into a struct or use the functional options pattern instead of reaching for a framework.

Avoiding interface pollution

An interface is a tool, not a decoration. These habits keep interfaces useful:

  • Do not create an interface for every struct "just in case". A one-implementation interface with the same methods as the struct adds indirection and a second thing to keep in sync.
  • Do not put interfaces in the producer package when they only help one consumer; define them in the consumer.
  • Do not use huge interfaces because a mocking tool generated them. Split by use.
  • Avoid any parameters when a small interface or a generic function would carry the type information. See The Empty Interface and any.
  • Prefer a plain function type when the behavior is a single operation with no state: func(string) error needs no interface at all.

Here is a quick way to decide. Reach for an interface when (1) several different types need to be used the same way, (2) you need to substitute behavior in tests, or (3) you want to depend on behavior instead of a particular package. Otherwise a concrete type, or a function, is simpler.

Go A function type instead of an interface

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Callers pass a literal function, with no named type and no method to write. If a second method appears later (say a Name() for logging), that is the moment to promote it to an interface.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Where should a Go interface usually be declared?

    Because satisfaction is implicit, the consumer can declare just the methods it needs. The implementing package does not need to know about it.
  2. 2. What does 'accept interfaces, return structs' recommend for a constructor NewCache?

    Returning the concrete type gives callers all methods and lets you add more later. Callers can still assign it to any interface they need.
  3. 3. Why is a hand-written fake with a method like Notify enough to test a service?

    The service depends on an interface, so any type with the right method set can stand in for the real dependency, and no mocking framework is needed.
  4. 4. Which situation is the best reason to introduce a new interface?

    Interfaces earn their keep when several types must be treated uniformly (or substituted in tests). Speculative interfaces are pollution.
  5. 5. What does type ClockFunc func() time.Time plus func (f ClockFunc) Now() time.Time { return f() } achieve?

    A function type can have methods. This adapter lets a plain function satisfy a one-method interface, the same trick as http.HandlerFunc.

Summary

  • Prefer small interfaces (one or two methods) and compose bigger ones from them.
  • Declare interfaces in the package that uses them, listing only the methods it calls; concrete types satisfy them implicitly.
  • Accept interfaces as parameters; return concrete types.
  • Test with small hand-written fakes and injected dependencies such as a Clock; no mocking framework is required.
  • Wire programs with plain constructors and a composition root in main; function types can adapt functions to one-method interfaces.
  • Do not add interfaces speculatively. If a plain function or a concrete type is enough, use that.

Next: Generics: Type Parameters starts the chapter on writing code that works for many types.