Friday, June 02, 2006

Code As Prose

Reading great code is like reading a great book. If you don't believe me, download Seaside or Dolphin Smalltalk. Of course, there's more examples than just that (Lisp 1.5 manual, Paul Graham's Lisp books, Structure and Interpretation of Computer Programs, etc), but I digress. You might now think I'm off my rocker and my brain is burnt from too much heavy metal music. But, I have a point to make.

There are simple rules to follow when writing: Outline your ideas; know your audience; and be concise. I'm sure there's more, but these are the three that I strive for. The funny thing is that these concepts correlate directly to code. Code is not merely communicating with the compiler and making things happen. If your software does anything of value or importance, it will be read by other people.

The act of design is the way we frame our ideas before we code. It allows us to plan out the high level view. It should not spell out everything, but give a blue print to how things will interface. It's the journey of thinking about the design that helps us. Code with a clear design is easier to maintain. Otherwise, it's a collection of incoherent thoughts glued together that might execute, but breaks often.

Writing your program for the computer is flat out wrong. In reality, the computer never really reads your code nor does it have to. It's the poor person awoken at three o'clock in the morning because a developer forgot to check for a null condition. It's the team interfacing their project on your library. In short, it's humans. We know this. Your audience is fellow developers. Take the extra time to name your variables well. Don't succumb to i,x,y, index, or each. Think about what business functionality you are implementing and write in that language. What if you had to give your code to someone non-technical? Could they understand what the code was doing? They should. Requirements live on in the program listing. Always strive for creating a domain specific language inside of your code.

Don't repeat yourself. I can't say it more simply. Don't be too clever and be concise. Prevent clutter from ruining the flow of a good program. Try to say the most with the least. It's good advice in art, writing, and programming.

There's probably more parallels that I could draw from, but I thought to keep this post simple. I enjoy reading books on good writing because I can try out new ideas for writing my code. I'm always asking myself how I could write something better for other developers to read. You can't learn from or maintain unreadable code. It's not hard to write well. It just takes practice. I'm amazed at how much code I read that is written for the computer. There's an over abundance of good code out there. The only way to become a great author is by reading great authors. Open source gives us a plethora of great code to admire and learn from. Get reading!

No comments:

Amazon