Code Koans

A collection of maxims from the world of computer programming

Programming rules of thumb

  1. Zero One Infinity rule: Arbitrary limits on the number of instances of a particular entity should not be allowed. An entity should either be forbidden entirely, one should be allowed, or any number of them should be allowed.
  2. DRY: Don’t Repeat Yourself.
  3. Rule of three: Code can be copied once, but when the same code is used three times it should be extracted into a new procedure.
  4. Gall’s law: A complex system that works is invariably found to have evolved from a simple system that worked. The inverse proposition also appears to be true: A complex system designed from scratch never works and cannot be made to work. You have to start over, beginning with a working simple system.
  5. Brooks’s law: “Adding manpower to a late softare project makes it later.” “Nine women can’t make a baby in one month.”
  6. “Hence plan to throw one [implementation] away; you will, anyhow.” –Fred Brooks
  7. 90-90 rule: “The first 90 percent of the code accounts for the first 90 percent of the development time. The remaining 10 percent of the code accounts for the other 90 percent of the development time.” –Tom Cargill, Bell Labs
  8. Pareto principle, a.k.a. 80-20 Rule: 80% of the effects come from 20% of the causes.
  9. “There are three hard problems in Comptuer Science, naming things and off-by-one errors.” –Old programming joke (as told by Yermo Lamers)
  10. Rubber ducking, a.k.a. Talk to the Bear: When debugging code, explain it line-by-line to another person, even if it’s just a rubber duck or teddy bear.
  11. Postel’s law: Be conservative in what you do, be liberal in what you accept from others.
  12. Sturgeon’s Revelation: Ninety percent of everything is crap.
  13. Hofstadter’s Law: It always takes longer than you expect, even when you take into account Hofstadter’s Law.
  14. Wirth’s law: Software is getting slower more rapidly than hardware becomes faster.
  15. Lehman’s laws of software evolution:
  16. Continuing Change – E-type systems must be continually adapted or they become progressively less satisfactory.
  17. Increasing Complexity – As an E-type system evolves its complexity increases unless work is done to maintain or reduce it.
  18. Self Regulation – E-type system evolution process is self-regulating with distribution of product and process measures close to normal.
  19. Conservation of Organisational Stability – The average effective global activity rate in an evolving E-type system is invariant over product lifetime.
  20. Conservation of Familiarity – As an E-type system evolves all associated with it, developers, sales personnel, users, for example, must maintain mastery of its content and behavior to achive satisfactory evolution. Excessive growth diminishes that mastery. Hence the average incremental growth remains invariant as the system evolves.
  21. Continuing Growth – The functional content of E-type systems must be continually increased to maintain user satisfaction over their lifetime.
  22. Declining Quality – The quality of E-type systems will appear to be declining unless they are rigorously maintained and adapted to operational environment changes.
  23. Feedback System – E-type evolution processes constitute multi-level, multi-loop, multi-agent feedback systems and must be treated as such to achieve significant improvement over any reasonable base.
  24. Greenspun’s tenth rule: Any sufficiently complicated C or Fortran program contains an ad hoc, informally-specified, bug-ridden slow implementation of half of Common Lisp.
  25. Zawinski’s law of software envelopment: Every program attempts to expand until it can read mail. Those programs which cannot so expand are replaced by ones which can.
  26. Amdahl’s law: The speedup of a program using multiple processors in parallel computing is limited by the time needed for the sequential fraction of the program.
  27. “Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live.” –John Woods
  28. “Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.” –Brian Kernighan
  29. You aren’t gonna need it (YAGNI): A principle of extreme programming (XP) that states a programmer should implement things only when they are actually needed, never when the need is just forseen.
  30. “We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil.” –Donald Knuth
  31. “In established engineering disciplines a 12 % improvment, easily obtained, is never considered marginal and I believe the same viewpoint should prevail in software engineering.” –Donald Knuth
  32. “I will, in fact, claim that the difference between a bad programmer and a good one is whether he considers his code or his data structures more important. Bad programmers worry about the code. Good programmers worry about data structures and their relationships.” –Linus Torvalds
  33. “The proper use of comments is to compensate for our failure to express ourself in code.” –Robert C. Martin
  34. “In programming the hard part isn’t solving problems, but deciding what problems to solve.” –Paul Graham
  35. “If debugging is the process of removing bugs, then programming must be the process of putting them in.” –Edsger Dijkstra
  36. “organizations which design systems … are constrained to produce designs which are copies of the communication structures of these organizations.” –Melvin Conway (Conway’s Law)
Abstraction principle

Each significant piece of functionality in a program should be implemented in just one place in the source code. Where similar functions are carried out by distinct pieces of code, it is generally beneficial to combine them into one by abstracting out the varying parts.

SOLID design
  1. S SRP Single Responsibility Principle
  2. O OCP Open/Closed Principle
  3. L LSP Liskov Substitution Principle
  4. I ISP Interface Segregation Principle
  5. D DIP Dependency Inversion Principle
CUPID design

Dan North’s rebuttal of SOLID.

  1. C Composable: plays well with others
  2. U Unix philosophy: does one thing well
  3. P Predictable: does what you expect
  4. I Idiomatic: feels natural
  5. D Domain-based: The solution domain models the problem domain in language and structure

Common code smells

  1. Duplicated code
  2. Long method
  3. Large class
  4. Too many parameters
  5. Feature envy: a class that uses methods of another class excessively
  6. Inappropriate intimacy
  7. Refused bequest
  8. Lazy class / Freeloader
  9. Contrived complexity
  10. Excessively long identifiers
  11. Excessively short identifiers
  12. Excessive use of literals / Magic numbers
  13. Ubercallback
  14. Complex conditionals

C++ Programming

  1. Rule of three: If a class defines one of the following it should probably explicitly define all three.
  2. With the advent of C++11 this rule is expanded to include:

PEP 20: The Zen of Python

  1. Beautiful is better than ugly.
  2. Explicit is better than implicit.
  3. Simple is better than complex.
  4. Complex is better than complicated.
  5. Flat is better than nested.
  6. Sparse is better than dense.
  7. Readability counts.
  8. Special cases aren’t special enough to break the rules.
  9. Although practicality beats purity.
  10. Errors should never pass silently.
  11. Unless explicitly silenced.
  12. In the face of ambiguity, refuse the temptation to guess.
  13. There should be one– and preferably only one –obvious way to do it.
  14. Although that way may not be obvious at first unless you’re Dutch.
  15. Now is better than never.
  16. Although never is often better than right now.
  17. If the implementation is hard to explain, it’s a bad idea.
  18. If the implementation is easy to explain, it may be a good idea.
  19. Namespaces are one honking great idea – let’s do more of those!

Unix philosophy

Doug McIlroy
  1. Write programs that do one thing and do it well.
  2. Write programs to work together.
  3. Write programs to handle text streams, because that is a universal interface.
Eric S. Raymond (ESR)
  1. Rule of Modularity: Developers should build a program out of simple parts connected by well defined interfaces, so problems are local, and parts of the program can be replaced in future versions to support new features. This rule aims to save time on debugging complex code that is complex, long, and unreadable.
  2. Rule of Clarity: Developers should write programs as if the most important communication is to the developers, including him- or herself, whom will read and maintain the program rather than the computer. This rule aims to make code readable and comprehensible for whomever works on the code in future.
  3. Rule of Composition: Developers should write programs that can communicate easily with other programs. This rule aims to allow developers to break down projects into small, simple programs rather than overly complex monolithic programs.
  4. Rule of Separation: Developers should separate the mechanisms of the programs from the policies of the programs; one method is to divide a program into a front-end interface and back-end engine that interface communicates with. This rule aims to let policies be changed without destabilizing mechanisms and consequently reducing the number of bugs.
  5. Rule of Simplicity: Developers should design for simplicity by looking for ways to break up program systems into small, straightforward cooperating pieces. This rule aims to discourage developers’ affection for writing “intricate and beautiful complexities” that are in reality bug prone programs.
  6. Rule of Parsimony: Developers should avoid writing big programs. This rule aims to prevent overinvestment of development time in failed or suboptimal approaches caused by the owners of the program’s reluctance to throw away visibly large pieces of work. Smaller programs are not only easier to optimize and maintain; they are easier to delete when deprecated.
  7. Rule of Transparency: Developers should design for visibility and discoverability by writing in a way that their thought process can lucidly be seen by future developers working on the project and using input and output formats that make it easy to identify valid input and correct output. This rule aims to reduce debugging time and extend the lifespan of programs.
  8. Rule of Robustness: Developers should design robust programs by designing for transparency and discoverability, because code that is easy to understand is easier to stress test for unexpected conditions that may not be foreseeable in complex programs. This rule aims to help developers build robust, reliable products.
  9. Rule of Representation: Developers should choose to make data more complicated rather than the procedural logic of the program when faced with the choice, because it is easier for humans to understand complex data compared with complex logic. This rule aims to make programs more readable for any developer working on the project, which allows the program to be maintained.[6]
  10. Rule of Least Surprise: Developers should design programs that build on top of the potentials users’ expected knowledge; for example, ‘+’ should always mean addition in a calculator program. This rule aims to encourage developers to build intuitive products that are easy to use.
  11. Rule of Silence: Developers should design programs so that they do not print unnecessary output. This rule aims to allows other programs and developers to pick out the information they need from a program’s output without having to parse verbosity.
  12. Rule of Repair: Developers should design programs that fail in a manner that is easy to localize and diagnose or in other words “fail noisily”. This rule aims to prevent incorrect output from a program from becoming an input and corrupting the output of other code undetected.
  13. Rule of Economy: Developers should value developer time over machine time, because machine cycles as of the year 2013 are relatively inexpensive compared to prices in the 1970s. This rule aims to reduce development costs of projects.
  14. Rule of Generation: Developers should avoid writing code by hand and instead write abstract high-level programs that generate code. This rule aims to reduce humans errors and save time.
  15. Rule of Optimization: Developers should prototype software before polishing it. This rule aims to prevent developers from spending too much time for marginal gains.
  16. Rule of Diversity: Developers should design their programs to be flexible and open. This rule aims to make programs flexible, allowing them to be used in other ways than their developers intended.
  17. Rule of Extensibility: Developers should design for the future by making their protocols extensible, allowing for easy plugins without modification to the program’s architecture by other developers, noting the version of the program, and more. This rule aims to extend the lifespan and enhance the utility of the code the developer writes.
Mike Gancarz
  1. Small is beautiful.
  2. Make each program do one thing well.
  3. Build a prototype as soon as possible.
  4. Choose portability over efficiency.
  5. Store data in flat text files.
  6. Use software leverage to your advantage.
  7. Use shell scripts to increase leverage and portability.
  8. Avoid captive user interfaces.
  9. Make every program a filter.
Worse is better
  1. Simplicity of both interface and implementation are more important than any other attributes of the system– including correctness, consistency, and completeness.
  2. Simplicity over perfection.

See Also