Brian Kernighan: The Elements of Programming Style
How to write good code, from one half of K&R C.
Video of talk at Institute of Advanced Study. Seemed to be given to computational astrophysicists?
~2:20: FORTRAN code example (identity matrix)
3:44: Introduces book he co-wrote called The Elements of Programming Style, first published in 1974. Takes bad code, improves it and derives a rule from that. The examples in that book are super-old but the talk takes the same approach, using more recent code examples. The principles of how to write well haven’t changed — only the details.
The Elements of Programming Style
- Don’t be too clever (@ 7:14)
- Simple things should be simple to understand when coded.
- Don’t be too dumb @ 9:14; keep it simple (@ 10:25)
- Understand the language (@ 12:53, 14:00)
- Don’t mix logical and arithmetic operators (@ 16:04)
- Figuring out operator precedence can be tricky, and mixing the types of operators can make it even trickier.
- Avoid macros in C and C++ (@ 19:34)
- Gives an example of calling a function defined by a macro, using as an input a something with a side-effect. So the implementation of the function changes how many times the side-effect occurs.
- Used to be used because they didn’t carry the overhead of a function call — important when processing power was scarce.
- Don’t sacrifice clarity for efficiency (@ 22:20)
- “Modern compilers on modern machines are just smarter than you are.”
- Avoid the bad features of a language (@ 25:17)
- Know the pitfalls (of otherwise good language features) (@ 27:18)
- Know the idioms of your language (@ 29:49, 32:51, 35:05)
- Test boundary conditions (@ 37:16)
- Program defensively: check parameters (@ 38:48), don’t trust input (@ 41:47), watch for overflows (@ 45:06)
- Avoid chains of lots of ‘if’ statements (@ 46:42)
- Readability gets hard. Better to use ‘else if’s such that every time you make a decision, you do something. (ie if, else if, else if, else rather than if, if, if, else, else, else.)
- Avoid mixing data and code (@ 50:23)
- Ideally separate the two. Code should be regular, with any irregularity lying within the data.
- “Data’s the place where you put the dirty stuff; code is the place where you want to keep it as clean as possible.”
- DRY (no official title) (@ 51:55)
- Modularise repeated code!
- Copying large tracts of code means that if there’s an update, you need to go find it in all the places in which it occurs. Much easier to fix if it only occurs once.
- HORRIFYING DEATH SOUND (@ 56:14 – 56:34)
- Comments on comments
- Make sure code and comments agree (@ 57:14)
- Don’t just echo the code with comments (@ 58:11)
- Make every comment count (@ 58:58)
- Don’t document bad code — rewrite it (@ 59:55)
- A red flag for this is a high comment density per line
- Avoid magic numbers (@ 1:00:59)
- Use names that mean something (@ 1:02:27)
- Summary (@ 1:03:29)
Say what you mean, simply and directly. Write as clearly as you can.