Media Gallery

Thoughts on Coding Style

Based on the Linux Kernel Coding Style document by Linux Torvalds.

This document targets mainly linux kernel programmers, but after many years of programming I personally think these are good basic guidelines and holds good rational for keeping maintainable code in general when programming several languages with various environments, and not just C. One of the most crucial things is to prevent unnecessary nesting. E.g. break a loop with an if false, instead of nesting true actions into it. Albeit, I've turned to using 4-space tabs instead of 8; and that's the nice thing about tabs, I can adapt the indentation with a single setting, instead of performing a reformat.


Good readability, prevents unnecessary deep nesting. Terminal and cross-editing friendly.
» Tabs at 8 spaces, thus indentations also at 8 spaces.
» Try to avoid more than 3 levels of indentation and stay within column/line-length 80.


Good readability. Keeps readability without wasting space.
» Opening brace on first line for control structures, next line if long statement(s) forcing multiple lines.
» Opening brace on next line for functions, wherever possible (compiler/parser interpretation).
» Closing brace on single end line, except when followed by a statement continuation (i.e. else if/do while).


Good readability. Keep it short, descriptive, and simple.
» Global variables and functions must have descriptive names. i.e. count_active_users() NOT cntusr().
» Local variables and functions should have short and to the point names. i.e. tmp vs ThisVariableIsATemporaryCounter, i vs loop_counter.


Good readability while keeping functions effective.
» Try not to exceed 5-10 local variables.
» Functions should be short and do one thing, and do that well.
» Use helper functions with descriptive names when writing long or complex functions.


Write code so it's easy to read, instead of commenting how it works.
» Comment about WHAT your code does, not HOW it does it.
» Functions should only need small comments to note or warn about something, or else it's too complex.
» Put functions on top of blocks, to tell WHAT it does and possible WHY it does it.

Original Post: Jan 28th, '22 00:35 CET.
Updated: Sep 26th, '22 12:07 CEST.

Tags: Misc