Do Unto Others…

I just read an excellent blog post by David Nimmo, called “Thinking of the next developer“, in which he shares a wonderful example of how a few moments of extra care can turn a complex and ugly function into one that is easy for other developers to read. His example was written in Haskell, but the principal is true in any language so I will demonstrate it in C#.

Imagine you are a developer asked to review the following code:

public string GetResponseFor(string message)
  if (message.Trim().Length == 0) return "Fine. Be that way!";
  else if ((message.Any(x => char.IsLetter(x)))
     && ((mesage.Equals(message.ToUpper()))))
     return "Whoa, chill out!";
  else if (message.Substring(message.Length-1)=="?") return "Sure.";
  else return "Whatever.";

If you are anything like me, as soon as you see a wall of text like that, your eyes just glaze over and you begin to question whether they pay you enough for nonsense like this. As David pointed out in his article, had the originator of this code been a little more considerate of the developers who came after him, he could have taken just two minutes to transform that mess into this:

public string GetResponseFor2(string message)
       if (IsEmpty(message))    return "Fine. Be that way!";
  else if (IsShouting(message)) return "Whoa, chill out!";
  else if (IsQuestion(message)) return "Sure.";
  else return "Whatever.";

Notice all the advantages of this latter example:

  1.  I, as the code reviewer, can look at this method for about three seconds and know exactly what the method is supposed to be doing. Of course, I still have to review the individual methods that encapsulate the logic, but when I do, I will know exactly what they are intended to do, making it much easier to evaluate the logic.
  2. Unit tests become obvious and easy. Imagine how convoluted the unit tests would have to be to support the original version.
  3. The logic is now re-usable. Other methods can call it without having to repeat it.
  4. It just looks better. Clean, organized, and aesthetically pleasing code just makes life better for the reviewer. And that reviewer may one day be me (or you).
  5. ADDED BONUS: No comments were necessary! (Which would have made the original code even uglier, by the way.)

So please, remember the golden rule of development: Do unto other developers as you would have them do unto you.

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s