A Simple Design Pattern for Clarity

I hate opaque flow control conditions, you know, “if clauses” with impenetrable conditions that defy reason without clarifying comments or extensive crib notes. The scenario is very common and not really something that’s easily avoided. In these cases, I tend to wrap the condition in a simple method (with no behaviour), where the name explains the test the condition is satisfying.
Here’s a very simple example:

if (usertype == "2" || usertype == "4" || usertype == "6")

This condition isn’t clear what it’s testing for. In fact, it’s testing to see if the user type is a category of user type, in this case a “business” user. So the pattern is just to wrap the condition inside a simple method, like so:

if (userIsBusinessType(usertype))

The new method is simplicity itself and could ostensibly be documented with a more extensive description of the condition being tested.

private static bool userIsBusinessType(string usertype)
return usertype == "2" || usertype == "4" || usertype == "6";

Superficially, this is an extremely simple pattern, but no one will dispute that it provides better clarity. However, importantly, when it’s compiled, it adds no more instructions for the condition to execute. That’s because we’ve added no behaviour to the condition, only an abstraction which can be optimized away by the compiler.
I use this pattern extensively. Good object orientation techniques and judicious use of extension methods mean that you can improve the pattern further, with an example like this:


But the basics remain the same. Either way it’s little touches like this that really apply the polish to good code for me.

  1. Leave a comment

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: