Friday, July 4, 2008

Expressing Intent

"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." -Martin Fowler et al, Refactoring: Improving the Design of Existing Code, 1999
I remember when I first started programming, I spent most of my time trying to understand what "the code" was doing. If you were anywhere near my cube, you'd might catch me saying things like, "what are you doing? why are you doing that? does anyone actually use you?"

The problem is that code doesn't "talk"! It doesn't tell you the reason for its existence. It merely exists. Some might use comments to help communicate intent, but that seems more like one is trying to apply deodorant to keep things fresh. The problem is that most antiperspirants or deodorant usually stop working after 24 hours. Eventually the comments are unable to mask the smell that bad code produces.

Here is an example of my favorite comment of all time:
//this variable is set to true for TeamTrac BUG #64322
boolean bool = false;
Wouldn't if be nice if you could simply look at code an almost instantly know what it wanted to do? Like most experienced programmers, I have a "feeling" for what I consider to be "good" code. One of the qualities I look for is "intent", because my experience tells me that doing so eliminates waste during development time.

The next time you are tempted to write a comment about what your code is trying to do, make it more explicit. This I doesn't mean that you have provide every detail in your method name either, just tell me what the "intent" is. For example:
updateProfileFeilds(firstName, lastName, userName, password)
works as good as
updateFirstNameLastNameUserNamePassword(firstName, lastName, userName, password).

I encourage you to refactor your code so that it expresses the intent. Instead of simply applying deodorant please keep your code clean! You will thank me six months from now when you won't have interrogate your own code, because you'll actually understand what its doing at a glance!

No comments: