The Code Codex
Theme
← Notes / Fundamentals

note · text08 Oct 2024 · 1 min

Interfaces

An interface is a contract: a set of methods that a type promises to have. Whoever uses the interface only knows the contract, not the implementation, so the implementation can change without touching its users.

Checkout

interface PaymentGateway

charge(amount)

StripeGateway

PixGateway

FakeGateway

(in tests)

Checkout

interface PaymentGateway

charge(amount)

StripeGateway

PixGateway

FakeGateway

(in tests)

In Java: explicit (nominal)

The class has to declare that it implements the interface:

interface Shape {
double area();
}
record Circle(double r) implements Shape {
public double area() { return Math.PI * r * r; }
}
In Go: implicit (structural)

There is no implements. If the type has the methods, it satisfies the interface automatically:

type Shape interface {
Area() float64
}
type Circle struct{ R float64 }
func (c Circle) Area() float64 { return math.Pi * c.R * c.R } // Circle is already a Shape

This lets you define the interface where it is used, not where the type is created. The Go convention is small interfaces, with one or two methods (io.Reader, io.Writer, fmt.Stringer).

What they are for in practice
  • Swapping implementations: the same code works with Stripe or Pix.
  • Testing: in tests, a fake implementation instead of the real service.
  • Decoupling layers: the domain defines the interface and the infrastructure implements it (the core idea of hexagonal architecture).

See also: Structs and interfaces in Go and Paradigms.