Code Koans
A collection of maxims from the world of computer programming
Programming rules of thumb
- 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.
- DRY: Don’t Repeat Yourself.
- 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.
- 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.
- Brooks’s law: “Adding manpower to a late softare project makes it later.” “Nine women can’t make a baby in one month.”
- “Hence plan to throw one [implementation] away; you will, anyhow.” –Fred Brooks
- 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
- Pareto principle, a.k.a. 80-20 Rule: 80% of the effects come from 20% of the causes.
- “There are three hard problems in Comptuer Science, naming things and off-by-one errors.” –Old programming joke (as told by Yermo Lamers)
- 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.
- Postel’s law: Be conservative in what you do, be liberal in what you accept from others.
- Sturgeon’s Revelation: Ninety percent of everything is crap.
- Hofstadter’s Law: It always takes longer than you expect, even when you take into account Hofstadter’s Law.
- Wirth’s law: Software is getting slower more rapidly than hardware becomes faster.
- Lehman’s laws of software evolution:
- S-programs are written according to an exact specification of what the program can do
- P-programs are written to implement certain procedures that completely determine what the program can do
- E-programs are written to perform some real-world activity; how they should behave is strongly linked to the environment in which they run, and these programs need to adapt to varying requirements and circumstances in that environment.
- Continuing Change – E-type systems must be continually adapted or they become progressively less satisfactory.
- Increasing Complexity – As an E-type system evolves its complexity increases unless work is done to maintain or reduce it.
- Self Regulation – E-type system evolution process is self-regulating with distribution of product and process measures close to normal.
- Conservation of Organisational Stability – The average effective global activity rate in an evolving E-type system is invariant over product lifetime.
- 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.
- Continuing Growth – The functional content of E-type systems must be continually increased to maintain user satisfaction over their lifetime.
- Declining Quality – The quality of E-type systems will appear to be declining unless they are rigorously maintained and adapted to operational environment changes.
- 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.
- 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.
- 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.
- 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.
- “Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live.” –John Woods
- “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
- 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.
- “We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil.” –Donald Knuth
- “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
- “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
- “The proper use of comments is to compensate for our failure to express ourself in code.” –Robert C. Martin
- “In programming the hard part isn’t solving problems, but deciding what problems to solve.” –Paul Graham
- “If debugging is the process of removing bugs, then programming must be the process of putting them in.” –Edsger Dijkstra
- “organizations which design systems … are constrained to produce designs which are copies of the communication structures of these organizations.” –Melvin Conway (Conway’s Law)
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.
- S SRP Single Responsibility Principle
- O OCP Open/Closed Principle
- L LSP Liskov Substitution Principle
- I ISP Interface Segregation Principle
- D DIP Dependency Inversion Principle
Dan North’s rebuttal of SOLID.
- C Composable: plays well with others
- U Unix philosophy: does one thing well
- P Predictable: does what you expect
- I Idiomatic: feels natural
- D Domain-based: The solution domain models the problem domain in language and structure
- Duplicated code
- Long method
- Large class
- Too many parameters
- Feature envy: a class that uses methods of another class excessively
- Inappropriate intimacy
- Refused bequest
- Lazy class / Freeloader
- Contrived complexity
- Excessively long identifiers
- Excessively short identifiers
- Excessive use of literals / Magic numbers
- Ubercallback
- Complex conditionals
C++ Programming
- Rule of three: If a class defines one of the following it should probably explicitly define all three.
- destructor
- copy constructor
- copy assignment operator
- With the advent of C++11 this rule is expanded to include:
- move constructor
- move assignment operator
- Beautiful is better than ugly.
- Explicit is better than implicit.
- Simple is better than complex.
- Complex is better than complicated.
- Flat is better than nested.
- Sparse is better than dense.
- Readability counts.
- Special cases aren’t special enough to break the rules.
- Although practicality beats purity.
- Errors should never pass silently.
- Unless explicitly silenced.
- In the face of ambiguity, refuse the temptation to guess.
- There should be one– and preferably only one –obvious way to do it.
- Although that way may not be obvious at first unless you’re Dutch.
- Now is better than never.
- Although never is often better than right now.
- If the implementation is hard to explain, it’s a bad idea.
- If the implementation is easy to explain, it may be a good idea.
- Namespaces are one honking great idea – let’s do more of those!
- Write programs that do one thing and do it well.
- Write programs to work together.
- Write programs to handle text streams, because that is a universal interface.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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]
- 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.
- 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.
- 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.
- 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.
- 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.
- Rule of Optimization: Developers should prototype software before polishing it. This rule aims to prevent developers from spending too much time for marginal gains.
- 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.
- 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
- Small is beautiful.
- Make each program do one thing well.
- Build a prototype as soon as possible.
- Choose portability over efficiency.
- Store data in flat text files.
- Use software leverage to your advantage.
- Use shell scripts to increase leverage and portability.
- Avoid captive user interfaces.
- Make every program a filter.
- Simplicity of both interface and implementation are more important than any other attributes of the system– including correctness, consistency, and completeness.
- Simplicity over perfection.
See Also