Sunday, June 1, 2008

What DRY is really about


Lets start with what the acronym DRY stands for, Do not Repeat Yourself. That sounds like a pretty good idea, it makes sense, but what are we really trying to accomplish by keeping our code DRY? Ok, that was a rhetorical question but I know someone out there would probably respond by saying "Not repeating ourselves!", to which the audience would chuckle because everyone knows that isn't what DRY is about. DRY is really about making high quality maintainable code.




Lately I have been finding things in the code base that I am working with that indicates that some programmers have taken DRY way too literally and use it in places that reduce code readability and maintainability. For example I found something similar to the following ruby on rails code a while back.


if something == true
temp_var = {:action => "foo"}
else
temp_var = {:action => "bar"}
end
redirect_to {:controller => "main"}.merge(temp_var)

In this example of code, they are essentially avoiding a tiny bit of duplication, defining the controller. The thing is this code is more difficult to understand than the following.

if something == true
redirect_to :controller => "main", :action => "foo"
else
redirect_to :controller => "main", :action => "bar"
end

In the second example there is a slight bit of duplication, but it is also easier to figure out what the code is doing as you read through your if statement. That increased readability makes the code just a little easier to maintain. Additionally if you were thinking about changing this code there is a good chance that you would be changing the controller argument for only one of the two redirect calls, in which case the second code example is much simpler to edit. Of course there is another option, if the person writing this code originally had been aware of some additional functionality that the rails framework offers they would have used a named route which would get rid of all of the duplication while maintaining great code readability.

if something == true
redirect_to foo_url
else
redirect_to bar_url
end

Now that you know DRY isn't just about not repeating yourself, take a little extra time before removing duplication and think about whether the change gets you closer to the goal of having readable and maintainable code. If the change doesn't make your code easier to maintain consider leaving the duplication or even better do some research and find a solution that gets rid of the duplication without making things harder to read or maintain.

No comments: