Linux kernel coding style

Of course, you have heard of the “never use GOTO statement” mantra, and of course, you are terrified not to follow the mantra. But why there is a lot of such statements in the linux kernel? Or why should you write as a few comments as possible?

What can we learn from the coding style of the project to which thousands of developers contributed?

If only the one thing I could extract from the linux kernel coding style, it would be the pragmatic approach to coding style. There is no one ideal and ubiquitous solution for everybody and every project.

Linus is the primary maintainer of the linux kernel. He is a gatekeeper, and he is a filter. Linus works a lot with the code written by other developers. And he needs to read a lot and to understand a lot. Any developer from any point of the world can submit a patch to the kernel. It is better to have a consistent style dictated by the person responsible for the project than trying to find the common denominator that can satisfy all the participants. It won’t help anyway because you will always find two developers with opposite views on coding style.

Indentation

Let’s start from indentation. I won’t open a holy war, I want to pay attention to how programmatic is the linux kernel coding style:

The critical moment is that the coding style is optimized for looking at the screen for 20 straight hours.

Functions

There is an old and well-known single responsibility principle for functions:

How can you argue with this?

Every time you update your code, you also need to update your comments. So there is one more entity that you need to support when changing the code:

The case for GOTO

The case is not apparent for developers coming with experience from garbage-collected programming languages like Java.

Example is taken from the block “7) Centralized existing of functions”:

So, in this example, you have less error-prone code. Because if you change the last block with the label, you don’t need to be afraid that somewhere in the function, you need to update a return statement. You have one centralized block to free resources.

But in Java, you can achieve the same behavior with the try-with-resources statement.

Do not be afraid to deviate from the standard or accepted coding style of your language except Go. You need to adapt it for your needs and the needs of your team to make your job more productive and engaging.

Originally published at https://scalabledeveloper.com.

I write about software engineering and my life journey.