Sunday, June 2, 2013

The holy laws of coding

Well, here we go. My holy laws of coding. Let there be irritation, indignation and infuriation.

  1. You shall not use tabs
  2. You shall not use bad names
  3. You shall not ignore the idioms and style guide
  4. You shall not write more than 80 characters per line

  5. You shall not write more than 10 lines per function
  6. You shall not write more than 10 functions per class/module/file
  7. You shall not duplicate code

  8. You shall not use a file when you can use a data structure
  9. You shall not ignore the libraries
  10. You shall not miss to refactor your code

To help coding novices, I designed 10 "holy laws", which I think are useful guides to write "good" code (whatever THAT is). I prefer to call them laws because rules are too easily broken but they can and should be broken IF there is a good reason.

Why are they important? What are the benefits? More details will follow in subsequent posts but as an outline: I think there are three main issues beginners struggle with that these laws try to address.

  • Readability
  • Complexity
  • Efficiency

Readability: Due to lack of experience beginners tend to write code that is difficult to read by other and themselves. The first four laws aim to improve readability.

I believe the mind of an experienced programmer works a bit like that of an experienced chess player. An advanced player sees a position and with one look acquires a rough understanding of its possibilities and flaws. Similarly, an advanced programmer often can get an understanding what a piece of code does, just be glancing at it. However, if one swaps chess pieces with jelly beans or writes code that violates the common style, understanding is much harder to gain.

Complexity: What causes beginners and multi-million dollar projects to fail is unmanaged complexity. A function with thousand lines of code or hundred functions with 10 lines: to the machine it is the same but to the human mind it is entirely different. Complex problems not broken into small and independent pieces are a certain recipe for disaster. Rules 5 to 7 help to manage complexity and violating them will limit the difficulty of problems one can solve.

Efficiency: Programming novices tend to ignore available libraries or data structures and stick to simple file-manipulation approaches that are inefficient and error prone. Rules 8 to 10 aim to increase efficiency and robustness, and also foster the progression of skills.

Finally have a look at How To Write Unmaintainable Code for great examples of bad code ;)

No comments:

Post a Comment