Monday, January 28, 2013

What vs. How

Have you ever had this happen to you? -- You're wading through code, analyzing one expression after another. After getting forty lines into the method, you pause and ask yourself, "Wait, what is this method supposed to do again?" It's easy to miss the forest for the trees.

This happens a lot when the code is overly focused on the How rather than on the What. Let's take a look at a short (and rather contrived) example. If you're not familiar with ColdFusion, don't worry -- just skim over it. You'll get the idea.

What's going on?

Why is this chunk o' code more intimidating than it needs to be ? Because once you get about half way through the method, you realize it's doing quite a lot. Here is What it's doing:

  • Configuring the mailer
  • Querying for the recipients
  • Filling in a message template
  • Adding up reward points
  • Logging results

All of this stuff might need to be done when you send out an email blast, but the problem is that the method doesn't clearly identify these steps -- it just dives right into the How of each one.

Hiding the How

When the How obstructs the What, the novice programmer tends to tack on comments above each code paragraph to help clue the reader into What's going on. Instead of doing that, you can extract each of those steps into its own method, which leaves you with something like this:

It's much harder to get lost in the details when you don't have any details! This second method is much less intimidating for two reasons.

  1. It's way shorter
  2. It focuses on What instead of How

Your Programming Language Can Help, Too!

Focusing on the What doesn't just mean extracting methods. It also means utilizing features of your programming language that are there to hide implementation. Some languages have built-in features like accessors, iterators, and event systems. Those are all there to help reduce the amount of code you have to write, and to help keep the implementation hidden in a deep place where you never even have to see it.

I Declare...

One final way you can help keep the focus on the What is to look for opportunities to write things declaratively instead of imperatively. Sometimes you can push complicated wiring out into configuration files, such as with many dependency injection frameworks. Other times you can use a language feature like annotations to mark up classes and methods.

By aiming for code that focuses on the What, you'll keep the How off where it won't get in your way when you're trying to grok your code again nine months from now!

No comments:

Post a Comment

Profile Picture
Dave Leeds
My Hobbies:
  • Programming
  • Cartooning
  • Music Writing
Full Profile