Thursday, 29 March 2012

"Copy-Paste" is really a problem? DRY-"Don’t Repeat Yourself" Principal

We’ve all seen it. We’ve all done it. Duplication! But why? In this post I will discuss some ways duplication happens in code. But first, why do we care about duplication?


It has been my experience that a majority of my time is spend maintaining code –even when writing a new application. Maintenance it’s not going away anytime soon. Therefore, the way to keep maintenance costs down is to speed up the task. The key to that is to make sure that “every piece of knowledge must have a single, unambiguous, authoritative representation within a system”.

The opposite of the statement above, is to express the same knowledge in multiple places. Which creates parallel maintenance –when one is changed the other must change. Can you say, “Hello bugs!”

This is where the “Don’t Repeat Yourself” (DRY) principle gets its roots. There are several ways that duplication happens, here are a few: 
  • When we are rushed or impatient. Sometimes eliminating duplication requires more time and effort. To remove duplication we have to modify our design. Whether it be extract a method, extract a class, etc –something has to change. But we say “it can wait, because it’s working and we don’t want to break it”. 
  • When we follow examples or ‘patterns’ that already exist in code. This is the easiest duplication to spot, but sometimes the hardest to remove. “Copy and paste is a design error”, says David Parnas. Instead, when possible, we should follow Object Orientated principles and use code generation tools to remove duplication. 
  • When we are unfamiliar with the code, which is caused by working in a team or being a new developer to a language. Sometimes we don’t know what classes and methods are available. Without due diligence during research we create duplication because we WILL write it ourselves. 
We must head off this maintenance nightmare by treating duplication as evil. Remove duplication as soon as it’s spotted.

Happy Coding!

No comments:

Post a Comment