Rule 1
Write simple code
- Simplicity is the ultimate sophistication [7]
- Use simple data structures and simple algorithms [3]
-
When in doubt use brute force
[4] -
A program/library should do one thing and do it well [2]
Unix got it right. While it might not be in the nature of a program to do one thing, any program can be designed as a combination of modules which do one thing. This improves testability and your ability to reason about the program and its components -
Follow the rule of three [11]
The rule of three should also be interpreted as: don't refactor before it's necessary
Rule 2
Write reasonable code
- You must be able to reason about all parts of your design, and the design as a whole
- Simple code is reasonable
-
basically, avoid comments. If your code needs a comment to be understood, it would be better to rewrite it so it's easier to understand
[3] - Do not the use semaphores and locks to access shared data [6]. Use message passing of data without pointers to shared data or callbacks
-
Functions should not have unexpected side-effects
E.g. library functions which prints a message when encountering an error
Rule 3
Write safe code
-
All loops and recursions must have a fixed upper bound [1]
Except loops that are ment to non-terminating -
The assertion density of the code should average to a minimum of two assertions per function [1]
Assertions should check for anomalous conditions that should never happen in real-life execution, and must be side-effect free. Assertions can be used to verify pre- and postconditions of functions, parameter values, return values of functions, and loopinvariants - Data objects must be declared at the smallest possible level of scope [1]
- Return values of all functions must be checked [1]
- Validity of function parameters must be checked at the start of each public function [6]
Rule 4
Keep everything short
- Short is readable; readable is reasonable
-
Short, descriptive variable names.
Length is not a virtue in a name; clarity of expression is
[3] - Functions should fit on a single piece of paper (about 60 lines of code) [1], and take no more than 6 parameters [6]
- Keep line width within 80 characters - it's not about screen size, but readability
Rule 5
Follow the Unix Philosophy [2] [9] [10]
References
- The power of 10: Rules for developing safety critical code
- Unix philosophy
- Notes on Programming in C
- Brute force
- Worse is Better
- JPL Institutional Coding Standard for the C Programming Language
- Simplicity quote
- The Magical Number Seven, Plus or Minus Two
- Wikipedia - Unix philosophy
- Revisiting the Unix philosophy in 2018
- Rule of three