Programming Mental Models

How do you think about code?

Chris Langager
3 min readMay 9, 2020

When you’re writing code, what are you actually doing? In the most literal sense, you are giving a computer instructions on what to do with a bunch of ones and zeros. Save them to a hard drive. Read them from memory. Send them over a network.

I’m guessing that’s not what you actually think about when you’re writing code. You probably have a “mental model” that is used to explain what your code is doing. I’ve been reading Dan Abramov’s Just JavaScript series, which is a wonderful deep dive into this subject. I highly recommend checking it out, whether you use JavaScript or not.

While reading one of the early articles, something jumped out at me that made me examine one of my own mental models:

On a clear night, I see the different values in the JavaScript sky: booleans, numbers, strings, symbols, functions and objects, null and undefined — oh my! I might refer to them in my code, but they don’t exist inside my code.

“Hold on,” you might say, “I always thought of values as being inside of my code!”

I’m positive that when I first started programming, I thought of “values as being inside of my code”. After all, where else could they be? I don’t remember when it happened, but at some point my mental model shifted. Values and references are not inside of my program, but sometimes, they fall through it:

A variable “falling through” code.

This idea was really solidified the more I learned about functional programming patterns. If there’s no mutation or external state, you can think of values falling through code as being deterministic, no matter how complicated the “physics” of your program. Take a look at the above animation again. The variable bounces through our code the same way every time it falls through.

By comparison, when code mutates values that are shared across functions (ie. global state), it calls no longer feels deterministic. One value may effect the other in chaotic ways:

Mutating shared state can lead to chaos.

This mental model is just one that I have, but I feel like it’s been a good guide for reducing complexity in my projects.

I’m now very interested in what mental models other people have and find useful. Just JavaScript has been a great window into the mind of a developer that I have a lot of respect for, but I want to hear from even more people. So that being said…

How do you think about code? Are you someone who thinks very literally about what your code is doing in terms of bytes and memory addresses? Or do you have your own version of my “falling through” example? I’d really like to hear about your mental models. If you have a good one, leave a comment!

The code used to make these animations was made using matter.js and can be found here. Gifs were made with GIPHY Capture.

--

--