Refactoring Tip: Introduce Explaning Variables
November 24th, 2008
I am not one to latch on to fancily named patterns, nor have I read the book on it (I did give it a skim). That said, I have managed to learn a few and today I’ll share one of my favorites. You often hear people say that comments are code smell. “You should be able to tell what code is doing by just looking at the code,” they say from their perch on high. Well, I hate to break it to you, but they are kind of right. Your code should be the comments. Take the following snippet of JavaScript code:
// if google.com or www.google.com add http:// to the href
if (typeof(scheme) == 'undefined' || scheme == 'www.') { url = 'http://' + url; }
This code is from some JavaScript I’m working on that performs auto-linking of urls and email addresses. Note that there is a comment and if you read the comment you get an idea of what the code is doing. Now I just stated that comments possibly smell, so what can we do to remove the comment and yet retain the intent of the code?
var no_scheme = typeof(scheme) == 'undefined',
www_scheme = scheme == 'www.';
if (no_scheme || www_scheme) { url = 'http://' + url; }
We just used a pattern, namely that of introducing explaining variables. The pattern probably seems obvious now that you see it, but how often do we code like the first example. In the example above, the explaining variables are introduced with the act of replacing the, not so obvious, conditions in the if statement, with variables that are named based on the intent of the condition. Our two lines of code are now three, but I guarantee the next programmer (which might even be yourself a few months later) in our code will appreciate that extra line. Everyone knows code gets changed quite often and comments rarely do which leads to confusing and out of date comments.
Next time you start busting out conditional statements or chaining methods together, consider how you could introduce an explaning variable that might make the code intent more clear.
If you enjoyed this post, get free updates by email or RSS.
Very nice and clean. Clever.
So true….and so much better than those “if (x and y) or (a and b) …..” type conditionals that sometimes you end up making. Good post!
I heard that whenever your testing for ‘undefined’ you should use the === operator.
Just my 0.2
Nice Blog!