Related Entries

Quick Start: Git for personal use
SVN client over SSH to remote Unix server from Windows
Quick Start Grinder - Part V
Quick Start Grinder - Part IV
Quick Start Grinder - Part III

« Managing your company to death
» Newbie SQL: Current week range

Practice of Programming - Style

Notes from an excellent book by great authors. First chapter.

I picked up The Practice of Programming by the great masters, Kernighan and Pike. I’m planning to find time to read a chapter every day and then note down the outline here. And then every month, wherever I’m, come back and browse through it!

Style

  1. Names
    • Use descriptive names for globals, short names for locals
    • Be consistent
    • Use active names for functions
    • Be accurate
  2. Expressions and statements
    • Indent to show structure
    • Use the natural form for expressions
    • Parenthesize to resolve ambiguity
    • Break up complex expressions
    • Be clear
    • Be careful with side effects
  3. Consistency and idioms
    • Use a consistent indentation and brace style
    • Use idioms for consistency
    • Use else-ifs for multi-way decisions
  4. Functions macros
    • Avoid function macros
    • Parenthesize the macro body and arguments
  5. Magic numbers
    • Give names to magic numbers
    • Define numbers as constants, not macros
    • Use character constants, not integers
    • Use the language to calculate the size of an object
  6. Comments
    • Don’t belabor the obvious
    • Comment functions and global data
    • Don’t comment bad code, rewrite it
    • Don’t contradict the code
    • Clarify, don’t confuse

Gem

Can you figure out what is wrong with this macro in C?
#define isupper(c) ((c) >= 'A' && (c) <= 'Z')

Try calling it like while (isupper(c = getchar()) and you will know what is wrong! Hint - instead of it being a macro, write it as a function.

Or, use a stylish language that simply won’t require you to waste time on making readable code.