Rule 1. As Simple as Possible, but No Simpler
Programming is hard.
I’m guessing you’ve already figured this out. Anyone who picks up and reads a book titled The Rules of Programming is likely to both:
-
Be able to program, at least a little
-
Be frustrated that it’s not easier than it is
There are lots of reasons why programming is hard, and lots of strategies to try to make it easier. This book looks at a carefully selected subset of common ways to screw things up and Rules to avoid those mistakes, all drawn from my many years of making mistakes of my own and coping with the mistakes of others.
There’s an overall pattern to the Rules, a common theme that most of them share. It’s best summarized with a quote from Albert Einstein describing the goals of a physical theorist: “As simple as possible, but no simpler.”1 By that, Einstein meant that the best physical theory was the simplest one that completely described all observable phenomena.
Recasting that idea to programming, the best way to implement a solution to any problem is the simplest one that meets all the requirements of that problem. The best code is the simplest code.
Imagine that you’re writing code to count the number of bits set in an integer. There are lots of ways to do this. You might use bit trickery2 to zero out a bit at a time, counting how many bits get zeroed out:
intcountSetBits(intvalue){intcount=0;while(value){++count;value=value&(value-1);}returncount;}
Or you might opt ...