Human-Readable Code

Prev don't be afraid of buying books Next

Every now and then I run across a piece of code that so impresses me, I spend the next several months and years telling people about it. Such was the case when I studied a piece of code written by Ward Cunningham. If you don't know Ward, you may know one of his many excellent innovations. Ward pioneered Class-Responsibility-Collaboration (CRC) cards, the Wiki Web (a simple, fast, read/write Web site), extreme programming (XP), and the FIT testing framework ( http://fit.c2.com).

The code I was studying came from a fictional payroll system that was meant for use in a refactoring workshop. As one of the workshop instructors, I needed to study this code prior to teaching. I began by looking over the test code. The first test method I studied checked a payroll amount based on a date. What immediately struck my eye was the date. The code said:

 november(20, 2005) 

This code called the following method:

 public void Date november(int day, int year) 

I was surprised and delighted. Even in a piece of test code, Ward had taken the trouble to produce a thoroughly human-readable method. If he had not cared to produce code that was simple and easy to understand, he could have written this:

 java.util.Calendar c = java.util.Calendar.getInstance(); c.set(2005, java.util.Calendar.NOVEMBER, 20); c.getTime(); 

While the above code produces the same date, it doesn't do what Ward's november() method does, which:

  • Reads like spoken language

  • Separates important code from distracting code

Now here's a very different story. It involves a method called w44(). I discovered the w44() function in a heap of Turbo Pascal spaghetti code that passed for a loan risk calculator for a large Wall Street bank. I spent the first three weeks of my professional programming career exploring this morass of code. I eventually figured out that 44 is the ASCII symbol for a comma, and "w" stands for "with." So w44() was the programmer's way of communicating that his routine returned a number, formatted as a string with commas. How intuitive! Either the programmer was shooting for big-time job security or he just didn't have a way with names.

Martin Fowler said it best:

Any fool can write code that a computer can understand. Good programmers write code that humans can understand. [F, 15]

Amazon


Refactoring to Patterns (The Addison-Wesley Signature Series)
Refactoring to Patterns
ISBN: 0321213351
EAN: 2147483647
Year: 2003
Pages: 103

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net