Skip to main content

SOLID in Go

Learning objectives
  • Explain each SOLID principle with a payments or order-management example, in Go terms rather than Java terms
  • Design small, consumer-defined interfaces and apply "accept interfaces, return structs"
  • Recognize Liskov violations in a language without inheritance and prevent them with contract tests
  • Wire a service with dependency inversion and a composition root, without a DI framework
  • Argue when SOLID is being over-applied and what the idiomatic Go alternative is

TL;DR​

  • SRP — a module has one actor (one group of people) who asks it to change. Split by reason to change, not by method count.
  • OCP — add a new payment method by adding code, not by editing checkout. Concentrate the remaining switch in the composition root.
  • LSP — every implementation must honor the interface's behavioral contract: errors, idempotency, blocking, side effects. "Silently succeed" is the classic violation.
  • ISP — the bigger the interface, the weaker the abstraction. Consumers declare the one or two methods they need.
  • DIP — business policy owns the interfaces; adapters (Postgres, Stripe, Kafka) implement them; main wires them together.
  • Go idiom: accept interfaces, return structs; discover interfaces when a second implementation (often a test fake) appears, do not design them up front.
  • Over-application looks like IPaymentService + PaymentServiceImpl, an interface per struct "for mocking", factories returning interfaces, and reflection-based containers.

Why it matters​

A payment or commerce platform changes along predictable axes: new payment methods (cards, wallets, QR, BNPL), new PSPs per market, new regulatory rules, new fulfillment partners. SOLID is a toolkit for making those changes local: one new package plus one line of wiring, instead of edits across checkout, refunds, reconciliation and their test suites.

Go changes how SOLID applies. There is no inheritance, so most of the classic LSP discussion about subclasses disappears, and interfaces are satisfied implicitly, so the consumer — not the producer — can define the abstraction. That one language feature makes dependency inversion almost free and makes Java-style "interface for everything" unnecessary. Interviewers at banks and e-commerce companies often have Java/.NET backgrounds; being able to explain why the Go version looks different is a strong signal.

Core concepts​

PrincipleOne lineGo mechanismPayments example
SRPOne actor per modulePackages named for one responsibilityPricing, invoicing and notifications split out of OrderService
OCPExtend without modifyingInterfaces + registry built in mainNew wallet provider = new package + one map entry
LSPImplementations are substitutableBehavioral contracts, contract testsA COD provider must not fake a successful refund
ISPNo client depends on methods it does not useSmall consumer-defined interfacesRefund worker depends on Refund only
DIPPolicy does not depend on detailsImplicit interfaces, composition rootcheckout never imports stripe or database/sql

Single Responsibility Principle​

Martin's later formulation (Clean Architecture) is more useful than "do one thing": a module should be responsible to one, and only one, actor. The question is not "how many methods?" but "how many different groups of people will ask for changes here?"

// Before: four actors share one type. The pricing team, the platform team,
// marketing and finance all edit the same file and the same tests.
type OrderService struct {
db *sql.DB
mailer *smtp.Client
pdf *pdf.Renderer
tax *taxapi.Client
}

func (s *OrderService) Total(o *Order) money.Money { return money.Money{} } // pricing rules
func (s *OrderService) Save(ctx context.Context, o *Order) error { return nil } // SQL
func (s *OrderService) SendConfirmation(o *Order) error { return nil } // e-mail copy
func (s *OrderService) Invoice(o *Order) (InvoicePDF, error) { return nil, nil } // tax law

After the split, the pricing team owns pricing, finance owns invoicing, and notifications react to an OrderPlaced event (ideally via an outbox) instead of being called inline. A change to e-mail copy can no longer break order persistence.

In Go, SRP applies most naturally at the package level. If you cannot name a package without "and", "manager" or "util", it probably has more than one actor.

Open/Closed Principle​

Software entities should be open for extension, closed for modification (Meyer, 1988; popularized by Martin). In practice: add a variant by adding code, not by editing a working, tested core.

// Before: every new payment method edits checkout and re-tests all methods.
func (c *Checkout) Pay(ctx context.Context, o *Order, method string) error {
switch method {
case "card":
return c.stripe.Charge(ctx, o.Total, o.CardToken)
case "momo":
return c.momo.CreatePayment(ctx, o.ID, o.Total.Minor())
case "bank_transfer":
return c.va.IssueVirtualAccount(ctx, o.ID, o.Total)
default:
return fmt.Errorf("unsupported payment method %q", method)
}
}
// After: checkout depends on a capability it defines.
type PaymentMethod interface {
Pay(ctx context.Context, o *Order) (PaymentResult, error)
}

type Checkout struct {
methods map[MethodCode]PaymentMethod
}

func NewCheckout(methods map[MethodCode]PaymentMethod) *Checkout {
return &Checkout{methods: methods}
}

func (c *Checkout) Pay(ctx context.Context, o *Order, code MethodCode) (PaymentResult, error) {
m, ok := c.methods[code]
if !ok {
return PaymentResult{}, fmt.Errorf("%w: %s", ErrUnsupportedMethod, code)
}
return m.Pay(ctx, o)
}
// cmd/api/main.go — the composition root is the one place that knows
// every concrete method. Adding ZaloPay is one new package and one line here.
checkout := order.NewCheckout(map[order.MethodCode]order.PaymentMethod{
order.MethodCard: stripe.NewMethod(stripeClient),
order.MethodMoMo: momo.NewMethod(momoClient),
order.MethodBankTransfer: virtualaccount.NewMethod(vaClient),
})

Two caveats keep OCP honest:

  • You cannot be closed against every change. Pick the axis that has actually varied (payment methods, PSPs, fee schedules). A switch over a closed set such as order statuses is fine and often clearer.
  • The switch does not vanish; it moves. It now lives once in main instead of in checkout, refunds and reconciliation. That concentration is the win.

Liskov Substitution Principle​

Liskov and Wing's behavioral subtyping: anything that satisfies an interface must be usable wherever that interface is expected without the caller noticing. Go has no inheritance, but it has interfaces, and the method set is only the syntactic half of the contract. The behavioral half — error semantics, idempotency, blocking, side effects — is where violations hide.

Typical Go-flavored LSP violations in payment systems:

ViolationSymptom in production
An implementation returns nil for an operation it cannot performA cash-on-delivery "refund" succeeds; the customer never gets money back
Panicking with "not implemented"Refund worker crashes on the first marketplace-seller payment
A fake repository returns nil, nil where the real one returns ErrNotFoundUnit tests pass; production dereferences nil
A caching decorator returns stale balances where callers assume read-your-writesDouble spend in a wallet top-up/withdraw race
One PSP adapter is idempotent on the request key, another is notRetries double-charge only on one provider
An io.Reader that returns 0, nil foreverCopy loops spin at 100% CPU
// Violation: COD bolted onto an interface that assumes online refunds.
func (p *CashOnDelivery) Refund(ctx context.Context, id PaymentID, amt money.Money) (RefundID, error) {
return "", nil // "nothing to refund online" — the caller thinks it worked
}

The fix is usually to stop claiming a capability you do not have. Split the capability into its own interface and detect it — the same pattern the standard library uses for io.WriterTo and http.Flusher:

type Refunder interface {
Refund(ctx context.Context, id PaymentID, amount money.Money) (RefundID, error)
}

func (s *RefundService) Refund(ctx context.Context, p *Payment, amount money.Money) error {
r, ok := s.providers[p.Provider].(Refunder)
if !ok {
// Not refundable online: route to the manual bank-transfer refund
// queue with an audit trail instead of pretending it succeeded.
return s.manual.Enqueue(ctx, p.ID, amount)
}
refundID, err := r.Refund(ctx, p.ID, amount)
if err != nil {
return fmt.Errorf("refund payment %s via %s: %w", p.ID, p.Provider, err)
}
return s.payments.RecordRefund(ctx, p.ID, refundID, amount)
}

To make the behavioral contract executable, write a contract test suite that every implementation — the Postgres repository, the in-memory fake, a caching decorator — must pass:

// RunAccountRepoContract runs the same behavioral checks against any
// AccountRepository. If the in-memory fake drifts from Postgres, it fails.
func RunAccountRepoContract(t *testing.T, newRepo func(t *testing.T) AccountRepository) {
t.Run("missing account returns ErrNotFound", func(t *testing.T) {
repo := newRepo(t)
_, err := repo.Get(context.Background(), "acc_missing")
if !errors.Is(err, ErrNotFound) {
t.Fatalf("want ErrNotFound, got %v", err)
}
})
t.Run("save with stale version returns ErrConflict", func(t *testing.T) {
repo := newRepo(t)
ctx := context.Background()
acc := NewAccount("acc_1", money.MustNew(10_000, "VND"))
if err := repo.Save(ctx, acc); err != nil {
t.Fatal(err)
}
stale := *acc
acc.Version++
if err := repo.Save(ctx, acc); err != nil {
t.Fatal(err)
}
if err := repo.Save(ctx, &stale); !errors.Is(err, ErrConflict) {
t.Fatalf("want ErrConflict, got %v", err)
}
})
}

More on fakes and contract tests is on Testing Strategy.

Interface Segregation Principle​

Clients should not be forced to depend on methods they do not use. In Go this is the proverb "the bigger the interface, the weaker the abstraction", and the standard library is the model: io.Reader has one method, and io.ReadWriter composes two small interfaces.

// Package psp (the producer) exposes a concrete client with many methods.
type Client struct {
http *http.Client
baseURL string
}

func (c *Client) Authorize(ctx context.Context, req AuthorizeRequest) (Authorization, error)
func (c *Client) Capture(ctx context.Context, authID string, amount money.Money) error
func (c *Client) Refund(ctx context.Context, paymentID string, amount money.Money) (string, error)
func (c *Client) ListDisputes(ctx context.Context, since time.Time) ([]Dispute, error)
func (c *Client) SettlementReport(ctx context.Context, day civil.Date) (io.ReadCloser, error)
// Package refundworker (the consumer) declares only what it uses.
// Unexported: it is an implementation detail of this package.
type refunder interface {
Refund(ctx context.Context, paymentID string, amount money.Money) (string, error)
}

type Worker struct {
psp refunder
log *slog.Logger
}

func NewWorker(psp refunder, log *slog.Logger) *Worker {
return &Worker{psp: psp, log: log}
}

The benefits compound: the worker's tests need a five-line fake instead of a generated mock with fourteen methods; a PSP client change to ListDisputes cannot break the refund worker's build; and the interface documents exactly what the worker relies on.

type fakeRefunder struct {
got []money.Money
err error
}

func (f *fakeRefunder) Refund(_ context.Context, _ string, amount money.Money) (string, error) {
f.got = append(f.got, amount)
return "rf_test_1", f.err
}

Dependency Inversion Principle​

High-level policy must not depend on low-level details; both depend on abstractions — and the abstraction is owned by the policy side. In Go, implicit interface satisfaction makes this natural: checkout declares PaymentAuthorizer and OrderRepository; the Stripe adapter and the Postgres repository satisfy them without checkout ever importing them.

The import graph is what you check in review: arrows point inward, toward the domain, and only main sees everything.

// cmd/api/main.go — explicit wiring; no container, no reflection.
func run(ctx context.Context, cfg Config) error {
db, err := pgxpool.New(ctx, cfg.DatabaseURL)
if err != nil {
return fmt.Errorf("connect db: %w", err)
}
defer db.Close()

orders := postgres.NewOrderRepo(db)
payments := stripe.NewAdapter(stripe.Config{APIKey: cfg.StripeKey, Timeout: 5 * time.Second})
svc := checkout.NewService(orders, payments, clock.System())

srv := &http.Server{Addr: cfg.Addr, Handler: httpapi.NewRouter(svc)}
return serve(ctx, srv)
}

Note the distinction interviewers like to probe: DIP is the design principle (who owns the abstraction), dependency injection is the technique (pass dependencies in), and an IoC container is optional tooling. Go services usually do DI by hand in main; Google's wire (compile-time code generation) or Uber's fx (runtime) exist for very large graphs. DIP at the architecture level is the core of Clean & Hexagonal Architecture.

Accept interfaces, return structs​

// Accept narrow interfaces; return the concrete type.
func NewService(orders OrderRepository, payments PaymentAuthorizer, clock Clock) *Service {
return &Service{orders: orders, payments: payments, clock: clock}
}

// Avoid: returning an interface for a single implementation hides methods,
// forces callers to type-assert, and freezes the producer's guess of what
// consumers need.
func NewServiceBad(orders OrderRepository) CheckoutServiceInterface

// Compile-time proof that an adapter satisfies a port — cheap and explicit.
var _ checkout.PaymentAuthorizer = (*Adapter)(nil)

Why it works: callers get the full concrete API and can declare their own narrow interfaces over it later. Legitimate exceptions to "return structs": error; deliberately hiding an unexported implementation behind a stable interface (context.Context, hash.Hash); and factories whose whole purpose is to choose among several implementations at runtime.

A maxim often attributed to Rob Pike sums up the workflow: don't design with interfaces, discover them. Start concrete; introduce an interface when a second implementation appears — and in services that second implementation is very often a test fake for an I/O boundary.

Where SOLID is over-applied in Go​

Over-applicationSymptomIdiomatic alternative
An interface next to every struct "for mocking"interfaces/ package with 40 interfaces mirroring structs; mockgen for eachConsumer-defined interfaces only at I/O and context boundaries
IPaymentService + PaymentServiceImplTwo names for one thing; Go reviewers flag it immediatelyOne concrete payment.Service
Constructors returning interfacesCallers type-assert; "go to definition" lands on an interfaceReturn *Service
SRP to the extremeOne method per struct, OrderValidatorFactoryProviderCohesive packages; functions are fine
OCP via plugins for rare changesConfig-driven plugin loading for something that changes once a yearA switch; refactor to a registry when the third variant appears
Reflection-based DI containersRuntime wiring errors, unreadable startupExplicit wiring in main
Wrapping the standard library wholesaleHTTPClientInterface, OSInterface, JSONMarshallerWrap only what you must substitute — typically the clock and external APIs
Getters and setters on every fieldJava-style ceremony, no invariants protectedExported fields for plain data; methods where invariants exist
Over-splitting packagesImport cycles "solved" with a types package everyone importsFewer, cohesive feature packages

The common root cause is treating SOLID as a checklist rather than as tools for managing observed change. Every interface is indirection the reader pays for; it should buy substitutability you actually use.

Trade-offs​

OptionStrengthsWeaknessesChoose when
Concrete types, no interfaceSimplest; "go to definition" worksHarder to substitute I/O in testsPure logic, value types, single implementation with no I/O
Consumer-defined small interfaceDecoupled; trivial fakes; documents real needsSeveral near-identical tiny interfaces across packagesDependencies on I/O, external APIs, other bounded contexts
Producer-defined interfaceOne shared definitionTends to grow large; couples all consumersThe producer genuinely has many implementations (database/sql/driver)
Strategy registry (OCP)Add variants without touching the coreIndirection; flow harder to traceThe axis has varied two or three times already
Plain switchObvious; whole picture in one placeCore edited for every variantClosed sets (order statuses) or few, stable variants
Hand wiring in mainExplicit, debuggable, compile-checkedVerbose in very large servicesDefault for Go services
wire / fxLess boilerplate for big graphsGenerated code or runtime magic to learnVery large services with many optional modules

In practice​

A checklist you can apply in review:

  • Does the domain package import infrastructure? checkout importing database/sql, stripe-go or a Kafka client is a DIP violation. The fix is a port interface in checkout and an adapter elsewhere.
  • Who defined this interface, and how many methods does it have? Interfaces in the consumer, one to three methods, are the norm. A producer-side 15-method interface is an ISP smell.
  • Is there one implementation plus a mock? Fine at an I/O boundary. Inside pure domain logic, prefer concrete types and real values in tests.
  • Can every implementation honor the doc comment? If one returns nil for "not supported", split the capability (LSP).
  • How many files does adding a payment method touch? More than "one new package plus one wiring line" suggests an OCP problem.
  • Is main small but complete? All New... calls live there or in a wire.go; no package-level singletons like db.Global.

Rough sizing intuition (team-dependent, not a rule): in a typical Go payment service, a handful of ports — order repository, payment provider, event publisher, clock, ID generator — is usually enough. Dozens of interfaces usually signal mocking-driven design.

Common pitfalls​

  • Interfaces defined by the producer "so others can mock it". Symptom: every change to the client regenerates mocks across ten repos.
  • "Not implemented" panics or silent nil returns in an implementation. Symptom: a crash or money not moved, only for one provider, discovered by customers.
  • Fakes that disagree with the real implementation. Symptom: green CI, red production — missing ErrNotFound, no optimistic-lock conflict, no unique-constraint violation.
  • OCP registries for things that never vary. Symptom: new joiners cannot find where a status transition happens.
  • Domain importing adapters through a "shared" package. Symptom: import cycles, and a domain unit test that needs Docker.
  • Package-level singletons (var DB *sql.DB) instead of injection. Symptom: tests cannot run in parallel; hidden coupling everywhere.
  • Confusing DIP with DI frameworks. Symptom: a reflection container introduced "to follow SOLID", startup failures at runtime instead of compile time.

Interview angle​

  • Common prompts: "Explain SOLID with examples", "How do you design for adding new payment providers?", "How do you test code that calls an external PSP?", "How does your Go code differ from Java here?"
  • A strong answer uses one domain consistently (e.g. payments) across all five principles, gives the Go-specific mechanism for each (consumer interfaces, implicit satisfaction, composition root), connects DIP to hexagonal architecture and testing, and volunteers where SOLID becomes harmful.
  • Follow-ups to expect: "How do you do LSP without inheritance?" (behavioral contracts, contract tests), "When would you return an interface?", "DIP vs DI vs IoC container?", "How do you avoid an interface explosion?"
  • Red flags: reciting definitions without examples, an interface per struct, believing OCP means "never modify code", or not knowing that Go interfaces are satisfied implicitly.

Self-check​

1. Restate SRP using the "one actor" formulation and apply it to an OrderService.

A module should be responsible to one group of stakeholders who request its changes. An OrderService that computes totals (pricing team), persists orders (platform team), sends confirmation e-mails (marketing/CRM) and generates invoices (finance/tax) serves four actors. Split into pricing, an order repository, a notifier reacting to OrderPlaced, and invoicing, so one actor's change cannot break another's feature.

2. Why can Go consumers define their own interfaces, and why is that awkward in Java?

Go interfaces are satisfied implicitly: any type with the right method set satisfies the interface without naming it, so a consumer can declare type refunder interface { Refund(...) } over a third-party client it does not control. In Java a class must declare implements X, so the interface must exist where the class is written — usually the producer — which pushes toward large producer-owned interfaces.

3. Give an LSP violation in Go and how you would prevent it.

A cash-on-delivery provider implements Refund by returning nil because there is nothing to refund online. Callers believe the refund succeeded and the customer is never repaid. Prevent it by splitting the capability (Refunder as a separate interface, detected with a type assertion and routed to a manual flow when absent), documenting the contract, and running a shared contract test suite against every implementation.

4. After the OCP refactor the switch over payment methods still exists in main. Have you really achieved OCP?

Yes, in the useful sense. OCP is about protecting the stable, tested core from modification. The variant selection now exists once in the composition root instead of in checkout, refunds and reconciliation; adding a method adds a package and edits only wiring. You can never be closed against all change — you pick the axis that varies and concentrate the remaining knowledge in one place.

5. When is returning an interface from a constructor justified?

When you deliberately hide an unexported implementation behind a stable contract (context.Context, hash.Hash), when the function's purpose is to choose among several implementations at runtime (a factory selecting a PSP by market), and for error. For a single implementation, return the concrete pointer so callers keep the full API and can define their own interfaces.

6. Scenario: you inherit a service with an interfaces/ package of 40 interfaces mirroring structs and a generated mock for each. Tests are brittle. What do you do?
  • Identify real boundaries (database, PSPs, message broker, clock) and move small interfaces into the packages that consume them.
  • For pure domain logic, delete the interfaces and test with real values.
  • Replace interaction-heavy mocks with fakes where state matters (repositories), backed by contract tests.
  • Do it incrementally, package by package, with characterization tests first — not as a big-bang rewrite.
7. Distinguish DIP, dependency injection and an IoC container.

DIP is a design principle: high-level policy owns the abstractions and low-level details implement them. Dependency injection is a technique: dependencies are passed in (usually via constructors) rather than created inside. An IoC container automates the wiring (Spring, fx). You can follow DIP with hand-written DI and no container — the default in Go.

🧠 Flashcards0/10 learned · 0 retries

Exercise​

You are given a psp.Gateway interface with 12 methods (authorize, capture, void, refund, tokenize, disputes, reports…) and a generated mock used by three packages: checkout, refundworker and reconciliation.

  1. Replace the shared interface with consumer-defined interfaces in each package (one to three methods each). Delete the mock and write small hand-rolled fakes.
  2. Add a cash-on-delivery provider without an LSP violation: it supports neither online capture nor refund, and refunds for COD orders go to a manual queue.
  3. Write RunPaymentRepoContract and run it against both an in-memory fake and a Postgres implementation (via testcontainers — see Testing Strategy).
  4. Draw the import graph of the result and confirm no domain package imports an adapter.

Done when: adding a hypothetical new provider touches only a new package plus main, go test ./... passes with no generated mocks, the contract suite passes for both repositories, and go list -deps ./internal/checkout shows no PSP SDK or database driver.

Further reading​

  • Robert C. Martin, Clean Architecture (2017) — SRP's "actor" formulation, DIP and component principles.
  • Robert C. Martin, Agile Software Development: Principles, Patterns, and Practices (2002) — the original SOLID chapters.
  • Dave Cheney, "SOLID Go Design" (GolangUK 2016 talk and blog post on dave.cheney.net).
  • Barbara Liskov and Jeannette Wing, "A Behavioral Notion of Subtyping", ACM TOPLAS (1994).
  • Bertrand Meyer, Object-Oriented Software Construction (1988) — origin of the Open/Closed Principle.
  • Effective Go — Interfaces
  • Go Code Review Comments — Interfaces
  • Google Go Style Guide — Best Practices — interfaces and dependency guidance.
Finished this page?

Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).