Abstraction with Interfaces
Definition
Abstraction
- In plain English
- Abstraction means exposing what something does while hiding how it does it.
- Think of it like
- It is like a car's pedals, where you press "go" without knowing how the engine works.
Interface
- In plain English
- A Go interface is a named set of method signatures that any type satisfies by having those methods.
- Think of it like
- It is like a job description, where anyone who can do the listed tasks qualifies.
Why it exists
Your clinic switches SMS providers. If reminder code names the old provider everywhere, you must edit each caller and retest each path.
Ask for the operation you need: notify this recipient. Reminder code stays the same when you switch delivery providers.
How it works
Implicit satisfaction
- In plain English
- Implicit satisfaction means a Go type fits an interface automatically by having its required methods.
- Think of it like
- It is like qualifying as a licensed driver by holding a licence with no extra sign-up.
package main
import "fmt"
type Notifier interface{ Notify(to, msg string) error }
type SMS struct{}
func (SMS) Notify(to, msg string) error { fmt.Println("SMS", to, msg); return nil }
type Email struct{}
func (Email) Notify(to, msg string) error { fmt.Println("email", to, msg); return nil }
func SendReminder(n Notifier, to string) error { return n.Notify(to, "Appointment tomorrow") }
func main() {
if err := SendReminder(SMS{}, "+10000000000"); err != nil {
panic(err)
}
if err := SendReminder(Email{}, "you@example.test"); err != nil {
panic(err)
}
}
Notifier requires Notify with recipient and message strings, returning an error. SMS and Email satisfy Notifier, and Reminders uses that interface.
- Keep interfaces small, often one or two methods.
- Define an interface in the package that uses it.
- Accept interfaces and return structs when callers need replaceable behaviour.
- T has value-receiver methods. *T has both receiver kinds. Use *T when the interface needs a pointer-receiver method.
Abstract class
- In plain English
- An abstract class is a half-built class in languages like Java that cannot be used on its own, and Go has no such thing.
- Think of it like
- It is like a half-finished template that must be completed before use.
Fake
- In plain English
- A fake is a simple stand-in implementation used in tests instead of the real thing.
- Think of it like
- It is like a crash-test dummy standing in for a real driver.
Examples
Appointment reminders
You send the same appointment reminder through SMS or email. Later, a push delivery type can provide the same Notify method.
package main
import "fmt"
type Notifier interface{ Notify(to, msg string) error }
type SMS struct{}
func (SMS) Notify(to, msg string) error { fmt.Println("SMS", to, msg); return nil }
type Email struct{}
func (Email) Notify(to, msg string) error { fmt.Println("email", to, msg); return nil }
func SendReminder(n Notifier, to string) error { return n.Notify(to, "Appointment tomorrow") }
func main() {
if err := SendReminder(SMS{}, "+10000000000"); err != nil {
panic(err)
}
if err := SendReminder(Email{}, "you@example.test"); err != nil {
panic(err)
}
}
Define Notifier beside the reminder code that uses it. Providers only need matching methods; they do not import the reminder package.
The insight
Callers depend on what, not how.
Average different hardware brands
Two hardware brands report readings through one Sensor contract.
package main
import "fmt"
type Reading struct{ C float64 }
type Sensor interface{ Read() (Reading, error) }
type BrandA struct{}
func (BrandA) Read() (Reading, error) { return Reading{C: 20}, nil }
type BrandB struct{}
func (BrandB) Read() (Reading, error) { return Reading{C: 24}, nil }
func Average(sensors []Sensor) (float64, error) {
if len(sensors) == 0 {
return 0, fmt.Errorf("no sensors")
}
total := 0.0
for _, sensor := range sensors {
r, err := sensor.Read()
if err != nil {
return 0, err
}
total += r.C
}
return total / float64(len(sensors)), nil
}
func main() { fmt.Println(Average([]Sensor{BrandA{}, BrandB{}})) }
The code combining readings checks for read errors and empty input. It does not need either device's temperature-reading details.
The insight
Interfaces hide hardware differences.
Test without paper
A test printer records job names instead of driving real hardware.
package main
import "fmt"
type Printer interface{ Print(job string) error }
type FakePrinter struct{ Jobs []string }
func (f *FakePrinter) Print(job string) error { f.Jobs = append(f.Jobs, job); return nil }
func Submit(p Printer, job string) error { return p.Print(job) }
func main() {
fake := &FakePrinter{}
if err := Submit(fake, "poster"); err != nil {
panic(err)
}
if len(fake.Jobs) != 1 || fake.Jobs[0] != "poster" {
panic("job not recorded")
}
fmt.Println("recorded one poster job")
}
Pass *FakePrinter because Print uses a pointer receiver. This lets the fake save the submitted job.
The insight
Abstraction makes testing cheap.
Trade-offs
Pros
- Swap implementations without changing callers.
- Test with inexpensive fakes.
- Reduce knowledge of implementation details.
Cons
- Following calls through interfaces takes extra reading.
- Interfaces without a purpose add clutter.
Use when
- The same caller needs two implementations.
- Tests need a fake.
Avoid when
- One implementation with no need for a test replacement.
- The concrete type already expresses the task well.
Quick check
Takeaways
- Abstraction = what, not how.
- Matching methods satisfy Go interfaces without an implements declaration.
- Keep interfaces small and define them where they're used.