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.

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_urlelse redirect_to bar_urlend

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.

8 comments:

ERPTREE handles oracle fusion HCM training and its modules maintaining classroom based training with the self-paced videos. An expert having ten plus years of self-experience handles the training period through online and explains each and every point perfectly. We recently launched our institute in the USA and getting the best reputation over there.