- Published on
Objects or Functions? Ask What Will Change
- Authors

- Name
- Mamun Rashid
I watched a video recently that compares object-oriented and functional programming on three small problems: checking a password, cleaning up a list of numbers, and keeping a log. For each one it lists pros and cons for both styles, then ends where most of these comparisons end. Mix them. Objects for structure, functions for logic.
I agree with the ending. Some of the reasons on the way there didn't sit right with me, though, and "mix them" doesn't tell me much when I'm staring at a half-written module. So I went back to a few older essays on the subject and wrote down how I actually decide.
Two ways to deal with moving parts
The framing I keep coming back to is a 2010 tweet from Michael Feathers (quoted here). Object-oriented code keeps a program understandable by wrapping each moving part up, so you deal with it through a small interface. Functional code takes the other road. In his words, "FP makes code understandable by minimizing moving parts."
Both are fighting the same thing: state you have to hold in your head while you read. That's why I don't see the two as rivals. Robert Martin argues the same in FP vs. OO. He boils each style down on purpose, OO to polymorphism and FP to referential transparency, and concludes that they're orthogonal but not mutually exclusive. A good program can lean on both.
So I don't ask which style is better. I ask which one fits the code in front of me, and two questions usually settle it.
What is going to change?
Picture the code as a grid. The rows are the kinds of things you handle, and the columns are the operations you run on them. For an auth system the rows might be password, OAuth and API key, and the columns verify, revoke and rotate.
Classes cut the grid into rows. Each auth method is a class that holds all of its operations. Functions over a tagged union cut it into columns. Each operation is one function with a case for every method.
Now add something. A new row is cheap with classes: one new class, and the existing methods stay as they are. With functions, every function needs a new case. A new column flips it. It's one new function on the functional side and a new method in every class on the object side. Try both:
Organize by
Next change
- · code that exists
- + code to write
- unit you edit
- interface AuthMethod unchanged
- PasswordAuth unchanged
- OAuth unchanged
- ApiKeyAuth unchanged
Pick a change to see what it costs.
This has a name, the expression problem, from a 1998 email by Philip Wadler. Eli Bendersky's write-up walks through it, along with the tricks some languages use to make both directions cheap. Most mainstream languages don't manage it, so you pick the direction you expect to grow in.
That turns the style question into a forecast. When I expect new kinds of things, say payment providers or file formats, I reach for an interface and classes. When the set of kinds is settled and I expect new questions about it, like another report or another export, I reach for a union and functions.
TypeScript makes either choice safe to get wrong, which is a big part of why I'm comfortable mixing. Add a method to an interface, and every class that implements it stops compiling until it has one. Add a case to a union, and every switch in a function with a declared return type stops compiling until it handles the case. The expensive direction is tedious, but the compiler hands you the list.
Where does the state live?
Something in every program has to change. A log grows, or a row gets written. The question I care about is how much of the code is allowed to do the changing.
Joe Armstrong, who created Erlang, described the worst case in Coders at Work (quoted here). You want a banana, and you get the gorilla holding it, plus the jungle. His complaint was the implicit environment an object drags around with it. To use one method you need the object and everything its fields point at.
The best answer I know is Gary Bernhardt's Functional Core, Imperative Shell. The decisions go in a core of pure functions that take values and return values. Around it sits a thin shell that does the I/O, like reading the database or calling the network.
In his example, the 165-line shell has no tests at all, because there's barely any logic in it. He tests the core by passing values in and checking what comes out, and none of those tests needs a mock. The core uses classes, too. They hold values and never reach out to the world, so they test just as easily. Near the end he says what matters isn't converting a whole program to this shape. It's noticing where mutation happens and keeping it in as few places as you can.
That's the second question. If a piece of code computes something, I want it in the core as plain functions. If it owns something over time, like a socket or a widget on screen, it's an object, and it lives at the edge.
The three examples, my way
Checking a password
The video gives this one to OOP when you need sessions and permissions, and to FP for a stateless API that just verifies passwords. It also says the class version breaks the open/closed principle as soon as you add OAuth or API keys, because you have to edit the class.
I'd push back on that last part. Having to edit the class is what happens when one class does everything. Polymorphism is the object-oriented fix: put the part that varies behind an interface, and a new auth method becomes a new class.
interface AuthMethod {
verify(attempt: string): Promise<boolean>;
}
class PasswordAuth implements AuthMethod {
readonly #hash: string;
constructor(hash: string) {
this.#hash = hash;
}
verify(attempt: string) {
return compareHash(attempt, this.#hash);
}
}
class ApiKeyAuth implements AuthMethod {
readonly #keyHash: string;
readonly #expiresAt: Date;
constructor(keyHash: string, expiresAt: Date) {
this.#keyHash = keyHash;
this.#expiresAt = expiresAt;
}
async verify(attempt: string) {
if (this.#expiresAt <= new Date()) return false;
return compareHash(attempt, this.#keyHash);
}
}
I'd pick classes here for the reason from the grid. Auth methods are a set I expect to grow, while the operations on them stay few. The #hash field is private at runtime too, not only to the type checker.
The video also says the functional version gives up encapsulation. A closure keeps a secret just as well:
function passwordVerifier(hash: string) {
return (attempt: string) => compareHash(attempt, hash);
}
Nothing outside that function can read hash. So encapsulation isn't what separates the two styles in this example. Which way the grid grows is.
Cleaning up a list
Dropping the negative numbers and doubling the rest is the easy one, and I agree with the video completely. A class that stores the numbers so a method can transform them adds state nobody needed.
const dropNegativesAndDouble = (numbers: readonly number[]) =>
numbers.filter((n) => n >= 0).map((n) => n * 2);
The video worries that longer chains get hard to read. They do, and the fix is the same as for a long method: give the steps names. Four named functions in a row read better to me than a class with four private methods passing a field between them.
Data in, data out is where functions win easily. They also combine well. My monoids post has a widget that shows why a lawful combine step can be split across workers without changing the answer.
Keeping a log
For logging, the video sets a logger class that keeps its entries against a functional version that returns a new list on every call, and then points out that all the copying costs memory.
I wouldn't keep the log as a list in memory in either style. Writing a log line is I/O, so it belongs in the shell. The interesting part, turning an event into a line, is pure:
type Level = 'info' | 'error';
type LogEntry = { at: Date; level: Level; message: string };
const formatEntry = ({ at, level, message }: LogEntry) =>
`${at.toISOString()} ${level.toUpperCase()} ${message}`;
class Logger {
constructor(private readonly write: (line: string) => void) {}
info(message: string) {
this.write(formatEntry({ at: new Date(), level: 'info', message }));
}
}
An object at the edge owns the effect, and a function in the middle owns the logic. You test formatEntry by calling it. You test Logger by handing it a write that pushes into an array. Neither needs a mocking library.
Three claims I'd soften
The video closes by comparing the styles on six points. Most of it holds up, but I'd put three of them more carefully.
On testing, it says OOP needs mocks and setup while FP doesn't. What forces a mock is code that reaches out to the world on its own, not the presence of a class. An object that takes its dependencies as arguments, like the Logger above, is as easy to test as a function. A function that calls fetch inside itself needs a mock too.
The performance claim is that objects and method calls add overhead and FP is usually more efficient. I wouldn't choose either style for speed. Immutable updates allocate new values, which the video mentions itself, and method calls aren't free either. Neither is usually where an app spends its time, and when something is slow I'd rather measure it than guess.
Last, thread safety. The video says FP is safe by nature because there's no shared state. Immutable values can be shared across threads without locks, and that's a real advantage. The program still has state somewhere, though. The log still has to land in a file. Functional style doesn't remove that coordination, it moves it into the shell. In Bernhardt's example only the main thread touches the database, so nothing races on it.
How I choose
Here's roughly the table I run through:
| If the code... | I reach for |
|---|---|
| will get new kinds of things, like providers or file formats | an interface and classes |
| will get new operations over a settled set of kinds | a tagged union and functions |
| turns data into other data | plain functions |
| owns something over time, like a socket or a UI widget | an object |
| talks to the database, the network or the clock | a thin shell with as little logic as I can manage |
The video's closing line, objects for structure and functions for logic, is close. I'd say it slightly differently. Use objects where something varies or holds on to a resource, functions where something gets computed, and push the mutation out to the edge.
John Carmack made a version of this point in Functional Programming in C++. A functional style helps in any language. Use it whenever it's convenient, and think hard before dropping it when it isn't. That's about where I've landed too. I start with functions, and I reach for a class when something really varies or really holds on to something.
Enjoyed this post?
Subscribe to get notified about new posts and updates. No spam, unsubscribe anytime.
By subscribing, you agree to our Privacy Policy. You can unsubscribe at any time.
Discussion
Loading comments...
This website is still under development. If you encounter any issues, please contact me.
Found this useful? Support the blog