Building the road — Code formatting

Charles Huet
3 min readSep 6, 2021

It seems widely accepted that reading a piece of code is harder than it is to write, so it makes sense that a lot of effort is spent trying to make the code easier to read. The most obvious factor that affects the code’s readability is formatting.

Code formatting refers to the way your code is laid out, where you put special symbols such as curly brackets, how much you indent the code and with which characters. There are endless debates about how to best format your code, but this is not what I want to talk about.
What I really care about is not how the code is formatted, but that the code is formatted consistently across the whole codebase.

Consistency of the formatting across the codebase makes the code easier to read, as one gets used to the patterns they encounter and recognizes them with greater ease every time. Looking over an unknown section of the code is made much easier by the patterns we easily recognize from repeated use.
It makes every part of the code feels like one, instead of having some mish-mash of styles, depending on who wrote which part of the code.

:’(

But automated code formatting is, in my opinion, the best way to work with code.

It avoids opinionated developers reformatting the code they have to edit because it does not fit their aesthetic sense. Which can sometimes be the source of conflicts, as the original developer can feel attacked by this reformatting.

Automation of code formatting forces the formatting rules to be consigned into the tool’s configuration, which should be inside of the repository to be picked up by IDEs to automatically format the code when saving the file.
Having this configuration inside the repository also enables automatic verification of the formatting by the CI pipeline, which ensures no badly-formatted code gets integrated. This allows developers to commit and push non-formatted code, which gives great flexibility in how one works, while keeping the main branch clean.
This allows new addition to the development team to be productive much faster, as they do not spend time learning the formatting conventions, and trying to memorize them.

This automation also ensures that debates on the code formatting have a dedicated place to happen, in the form of a merge request changing the configuration and applying it to the whole codebase. This makes these debates much more fruitful as the impact on the codebase is plain to see.

I find the ability to write code without thinking about whitespace quite liberating, as I no longer worry about an old habits taking over. Even if they do, the tool will put everything how it needs to be for this particular project.

auto format on save makes my life easier

--

--

Charles Huet

Software Engineer for over a decade, with a heavy focus on C++, and lots of time spent making buildsystems easier