The importance of a coding style

Posted on

As I (re)discover the world of coding, like a lot of people, I feel the need of keeping a coding style guide coherent throughout my scripts or programs. As up to now, I write C or python code (sometimes a bit of bash).

C code, kernel style guide

For C, I decided to take a clear decision that make sense. As I’m interested in embedded systems (especially because of my project Ears Wide Open) I looked at the kernel tree (at the moment I’m clearly lost in it) and especially at a video for newbies given by Greg Kroah-Hartman called “Write and Submit your first Linux kernel Patch”.

The coding style makes sense, they are using it for quite a while in maybe what is the biggest open source program ever created. Moreover, they wrote a perl script to test the syntax (among other things) that makes it easier to find the errors and ensure the coherence of the code for anyone who wants to contribute (maybe one day, I’ll pick the interest of others but it’s a bit soon for that).

Here some basics :

  • use tabs
  • tabs are 8 characters long
  • 80 characters limit

Of course, everyone can critisize these constraints but now that I’m writing a bit of C code, have tabs of 8 characters make the code easier to read (yes it’s possible with 4 characters either but it’s even more clear with clearer with 8) and sticking the limit of 80 characters force to refactoring when the code tends to go way other this limit. I my opinion, it’s a good thing.

For conditional statements, the opening brace ends after the condition (upper right) and closes on a blank line (lower left) such as:

if (error != -ENODEV) {
} else {
    goto exit;

If there is only one line in the condition then the braces are used anymore:

if (error != -ENODEV)
    goto exit;

Regarding the functions, here the example:

int function(int *baz)
    return 0;

For the rest, I invite you to look at the file Documentation/CodingStyle of the Linux kernel tree to know more. I will probably add this file to the repository of my project soon.

And for the lazy like me who uses VIm, there is a nice VIm script helping you to respect the kernel style guide.

Python, same story?

With python, I didn’t really end up far to choose a coding style guideline. First, because the language by itself returns errors if you don’t indent correctly your code (that’s a good thing). For the rest, I stick to the PEP8 style guide. The same way of the perl script for the kernel, it exists a python script to check the sanity of your python syntax scripts called pep8. Nothing fancy but very nice to have and keep easily your code writing coherent.