Sunday, April 01, 2007

A case for consistent (and beautiful) coding styles

As it's written in The Zen of Python (PEP 20), "Readability counts". Code is read much more often than written, so a nice looking source code is fundamental.

This is a criticism specifically aimed to the inconSistentCase that started to plague C++, C and even assembly code in the Internet, and, more generally, a criticism of ugly, useless coding styles, like pre/post-fixed notations, very long line styles, and, surely, inconSistentCase.

Whenever you write code or are in charge of deciding the coding style of your software, please, please, please, use consistent coding styles. For example, use full, first-letter-caps, CamelCase notation, not inconSistentCase. As for my personal coding style taste, do even more, minimize the amount of capitalized letters in your code and use the highly legible underscore_notation instead, like those used in most C code, in python and, especially, in C++ STL. Don't let your code strech to hundreds of characters per line and don't add completely useless "NrUserId" prefixed notations.

Here are many examples of nice, well thought coding styles, that you may adapt for your needs:
  • PEP 8: an exellent coding style guide for the python language. Mostly an underscore_notation style, with a little, easy on eye, CamelCase and post-fixed notation for special cases (ex: ClassNames, ExceptionsEndInError, etc.). The style is good for python and other high level languages, but it could be better for C++, which leads to...
  • STL: part of the C++ standard library, a good example of really well though piece of code. Uses full underscore_notation. If paired with selective namespace downloading (using std::vector, using std::string, etc.), will produce beautiful C++ code.
  • Xlib: Choose this one if you prefer a mostly CamelCase style. Even though Xlib is outdated and supposed to fade away, it was also a well thought library. It also shows a good way to add a namespace-like structure to a C library, using a single "X" prefix in most library functions.
  • linux kernel: Another great coding style for the C language. Useful for mostly non-object oriented, structured programming, but includes insightful hints for anybody (ex: local variables get short, "aux, tmp" names, external functions get long_descriptive_names, etc.), and is backed by the pseudo-chaotic-multi-million-people linux kernel development success.
There are many other projects that you may try that use similar, high legibility coding standards, just google for it. See, for example, Gtkmm, Gtk+ port to C++, the OpenTTD game, etc.

If you've found that all those coding styles are crappy (even after thinking of them in terms of readability), then you should just remember one thing from this post: don't use inconSistentCase, it sucks.

No comments: