I have been teaching computer programming for a while now and I have come up with several principles that help students make better coding choices. The goal is for the students to learn how to write efficient code that is also resistant to breakage. Here are my findings:
- Chekhov’s Gun – A ‘Chekhov’s gun’ is a literary technique made famous by the great playwrite, Anton Chekhov himself. He said “that any object introduced in a story must be used later on, else it ought not to feature in the first place.” It means “do not include any unnecessary elements in a story” or, in our case, in our code. Every line of code, object, and class that is included should be used leaving no loose ends.
- DRY – DRY stands for Don’t Repeat Yourself and was made popular by the people at The Pragmatic Programmers. In practical terms it means do not include redundant code. Write your code in such a way that there is no duplication of anything. This prevents errors when programs are edited later and not every instance of a needed change was implemented.
- Occam’s Razor – Occam’s Razor (or KISS – Keep It Simple, Stupid) “is a principle attributed to the 14th-century English logician and Franciscan friar William of Ockham.” The principle states that “the explanation of any phenomenon should make as few assumptions as possible.” It means that, all other things being equal, the simplest solution is usually best. So, attempt to keep your code as simple as possible. Search out the simplest solution since complex code is always inferior to simpler code that accomplishes the same task.
- The Mayonnaise Jar and Two Cups of Coffee – This simple principle comes from a popular story circulating on the Internet. Although the story speaks about life, it can be applied to programming. Basically, you should implement big features before smaller features. Big features include decision structures and looping structures – complex programming code that exists on multiple lines as opposed to one-liners.
And there are many more, but this list is a decent start. I will likely be adding to this list from time to time so check back in the future. If you just can’t wait, then browse the List of Tips posted with the The Pragmatic Programmer book by Andrew Hunt and David Thomas and read Getting Real by the people at 37signals. Until then, happy coding!