Part 2 of 10 · How we build

Object-oriented or functional: which style for which code?

Use objects where something has identity and state that must stay consistent, and pure functions over plain data for transformations, calculations and pipelines. Most good codebases mix the two. How to decide, with Go and TypeScript examples.

A green gear wheel on an old engine

The verdict, which the clues below earn: it isn’t a language choice; it’s a choice per piece of code.

  • Objects (data plus the methods that guard it) fit things with identity and a lifecycle, where some changes must be refused: an order, an account, a connection pool.
  • Pure functions over immutable data fit transformations: parsing, pricing, validation, formatting, data pipelines. Same input, same output, trivially testable.
  • Keep side effects at the edges (database, network, clock) and the logic in the middle pure. That one habit matters more than which paradigm you claim.

Case file

The case A shipped order cancelled, a price that changes by day, a lost counter update
Suspects “Too much OOP”, “not enough types”, “we should have gone functional”
Culprit The wrong style for that piece of code, and side effects mixed into logic
The fix Objects for lifecycles, pure functions for transformations, effects at the edges

The case #

A shipped order somehow gets cancelled. A pricing function returns a different answer on Tuesday. Two workers update the same counter and one update vanishes. The usual suspects get named on sight: “too much OOP”, “not enough types”, “we should have gone functional”.

It helps to stop treating these as rival gangs. Both traditions found something true about code; the detective work is noticing which truth a given piece of code needs.

The suspects at a glance #

Each style has a different centre of gravity:

Object-oriented Functional
Organises code around Things and their behaviour Data and the transformations applied to it
State Inside objects, changed by methods Passed in, returned new; not changed in place
Good at Protecting invariants; modelling lifecycles; swapping implementations behind an interface Composing steps; reasoning and testing; concurrency (nothing shared to change)
Typical failure Deep inheritance trees; logic scattered across classes; hidden shared state Unreadable chains of abstractions; awkward modelling of things that do change
Testing Needs setup of objects and often mocks Call the function, check the result
Flowchart: Does this code touch the database, network or clock?, Edge: thin, imperative, Does state have rules about how it may change?, Object or private type that guards it, Pure function over plain dataFlowchart: Does this code touch the database, network or clock?, Edge: thin, imperative, Does state have rules about how it may change?, Object or private type that guards it, Pure function over plain data
Diagram source
flowchart TD
  Q1{"Does this code touch the database, network or clock?"}
  Q1 -->|yes| E["Edge: thin, imperative"]
  Q1 -->|no| Q2{"Does state have rules about how it may change?"}
  Q2 -->|yes| O["Object or private type that guards it"]
  Q2 -->|no| F["Pure function over plain data"]

Use case 1: domain rules with a lifecycle #

The scene: an order moves from pending to confirmed to shipped. A confirmed order can’t gain lines; a shipped one can’t be cancelled.

What I’d use: an object (or a module with a private type) that owns the state and refuses illegal changes.

class Order {
  private constructor(private status: 'pending' | 'confirmed' | 'shipped', private lines: Line[]) {}
  addLine(l: Line) {
    if (this.status !== 'pending') throw new Error('confirmed orders are fixed');
    this.lines.push(l);
  }
  confirm() { /* check stock, totals; then */ this.status = 'confirmed'; }
}

The value here is encapsulation, and what I admire is how much it rules out: no other code can put an order into a state the business forbids. You can get the same guarantee functionally (a confirm(order) → ConfirmedOrder function and a type that has no addLine), and in TypeScript that’s often neater. Either way, the rule lives in one place.

Use case 2: data pipelines and calculations #

The scene: turn an uploaded spreadsheet into order lines: parse, normalise part numbers, match against the catalogue, compute prices, flag low-confidence rows.

What I’d use: a chain of pure functions.

rows := parse(file)
lines := normalise(rows)
matched := match(lines, catalogue)
priced := price(matched, contract)

Each step takes data and returns new data, and that buys a lot. You can test normalise with a table of inputs and outputs, run the steps in parallel, and replay a bad document exactly, like rerunning the tape of a crime. The part-number matching case is built this way. The false lead here is wrapping these steps in Parser, Normaliser and Matcher classes with one method each: that adds names, not value.

Use case 3: concurrent code #

The scene: several goroutines or workers process events and update shared counters or caches.

What I’d do: share as little mutable state as possible.

  • Pass immutable messages between workers (Go channels, queues) rather than sharing objects behind locks.
  • Where state must be shared, keep it in one owner (one goroutine, one actor, one database row) and send it requests.
  • Pure functions are safe to call from anywhere; objects with mutable fields need a lock or a single owner.

This is where functional habits pay most, and the motive is simple: most concurrency bugs are two pieces of code changing the same thing.

Inheritance: the part of OOP to use least #

Interfaces and composition age well; deep inheritance doesn’t. The good news is that OOP’s best ideas don’t depend on it.

  • Prefer interfaces for “anything that can do X”. The email code in the blogging platform I run has one: Sender with a single Send method, implemented by SMTP, several HTTP providers, a log sender for development and a recorder for tests.
  • Prefer composition (“has a”) over inheritance (“is a”) for sharing behaviour.
  • Use inheritance only for shallow, stable hierarchies, usually ones a framework asks for.

Go has no inheritance at all, and large Go codebases don’t miss it.

The reveal: a practical mix #

Put the clues together and a shape emerges that works in most services:

  1. Edges (HTTP handlers, queue consumers, database code): imperative, with side effects, as thin as possible.
  2. Core (rules and calculations): pure functions over plain data, plus a few objects or types that guard lifecycles and invariants.
  3. Interfaces only where you have, or will soon have, more than one implementation.

This is sometimes called functional core, imperative shell, a phrase Gary Bernhardt popularised; the architecture styles case takes it further. It’s a neat solution: it makes the core testable without mocks and keeps the messy parts small.

Remember this

  • Choose the style per piece of code, not per language.
  • Functional core, imperative shell.
  • Prefer interfaces and composition, and avoid inheritance beyond one level.

What I’d do on Monday #

  1. Write plain functions over plain data first.
  2. Introduce an object or private type when a piece of state has rules about how it may change.
  3. Use interfaces for real variation, not for every dependency.
  4. Avoid inheritance beyond one level.
  5. Push side effects to the edges and keep the core pure.

The best code I’ve read borrows freely from both traditions. Each paradigm comes from people who thought hard about what makes code easy to change, and both are worth learning from.

Like (sign in first) 0 likes 💬 0

Written by

Vishal Kumar

Associate Director at CapGrid, running product and engineering in a CPTO capacity. 10+ years building distributed, multi-tenant SaaS and AI platforms. AWS Certified Solutions Architect - Professional. Based in Gurugram.

Comments

No comments yet.

Sign in to comment. We'll email you a link; no password needed.