Brain friendly programming

Apr 25, 2024 11:03 am

Hi ,


We have many principles for writing better more maintainable software, but somehow we sometimes still end up with a tangled mess.


Most of us have heard about the Single Responsibility Principle, https://en.wikipedia.org/wiki/Single-responsibility_principle. Robert C Martin expressed this principle as "A class should have only one reason to change".


He later clarified this by stating "Gather together the things that change for the same reasons. Separate those things that change for different reasons".


We also have the Single Layer of Abstraction Principle which is expressed as "Don't mix levels of abstractions".


Dan Terhorst-North presented his Unix Philosophy expressed as "does one thing well". https://dannorth.net/cupid-for-joyful-coding/


So what does these principles actually mean, how can I as a developer use them to create better software?


I recently read a book and re-watched a presentation that changed the way I think of these principles.


In "The Programmer's Brain", Dr Felienne Hermans talks about how our brain works when we are working with code. https://www.manning.com/books/the-programmers-brain. It's a really interesting book and a recommended read.


One of the key take-aways for me was the fact that our working memory can only keep track of 3 - 5 chunks of information at the same time. The size of a chunk depends on how much experience we have with the current task.


It can be individual statements, lines or entire design patterns.


We can make our code easier to understand, to lower the cognitive load of the reader, by limiting the number of chunks of information we have to keep track of at the same time.


Ok, so how do we do that then?


This is when the presentation "Simple made Easy" from Rich Hickey, https://www.infoq.com/presentations/Simple-Made-Easy/, comes in.


He talks about how we complect our code.


Complect is a old word that means to braid together, to weave together. By complecting our code we make in harder to understand by requiring the reader to keep more chunks of information in memory at the same time. We are increasing the cognitive load for the reader.


He suggests that we should separate our code based on the questions, what? who? how? when? where? and why?.


I feel that it is easier to think and talk about these questions compared to wondering if I'm violating a principle. This have helped me write better code that is easier to read and understand and I hope it can be of some use to you too.


I'm currently working on a blog post around this subject and would love for your feedback. Please reply with your thoughts.


Enjoy,

Markus Westergren

Comments