Interfaces and composition
Define the behavior you consume.
The idea
Go satisfies interfaces implicitly. The booking operation can define the small persistence behavior it requires, while the PostgreSQL adapter implements it without naming that interface. Compose behavior through fields and methods rather than an inheritance tree.
Follow the flow
Make it concrete
This excerpt isolates the concept. Connect it to the booking API as you work through the exercise.
type Saver interface {
Save(context.Context, Booking) error
}
type Reserve struct { store Saver }
func NewReserve(store Saver) Reserve {
return Reserve{store: store}
}Decisions that matter
- Small interfaces make dependency direction visible.
- Accept interfaces when substitution protects a useful boundary.
- Do not introduce an interface for every concrete type automatically.
Your turn
An adapter implements twenty methods but the use case needs one. How large should the consumer interface be?
Reveal a worked answer
Define the one operation the use case consumes. This limits coupling and makes a test fake small. Avoid producing a shared giant repository interface merely because an adapter offers many methods.