Don’t Repeat Yourself

January 27, 2010

Don’t Repeat Yourself

Today while I was Don’t Repeat Yourself
doing code review
I found myself
writing a new
generic function
instead of one
piece of code
that was repeating
itself in the
developer’s code.
When you write
code sometimes you
have to duplicate
some piece of code.
When it occurs, this
is the best time to
think of refactoring your functionality.
A lot has been written about DRY principal this post is my opinion
about it.

The DRY Principal

Don’t Repeat Yourself or DRY is a very good practice when we are
writing code. It helps to produce a more reusable and maintainable
code. When you don’t follow DRY whenever a functionality that
you “Copy & Paste” all over your code will change you’ll have
the taste of one of the developer horrors –
to find all the places in the application that you duplicated the
functionality and to update it. Not being able to find all the places will
result in a non functioning application or other errors. Since changes 
always occur during the life time of an application following the
simple DRY principal can prevent you a lot of headaches.

Example

Lets look at the code that I helped the developer to refactor:

private void ValidateContactDetails()
{
   var validator = ValidationFactory.CreateValidator<ContactDetails>();
   var results = validator.Validate(uc.DataSource);
   if (results.Count > 0)
   {
      ValidationError.DisplayError(results.First().Message);
   }
}

This code validate a contact details entity using the

Validation Application Block. Since the code was repeated in more

than one place but with different object types and different data

sources then I created the following method instead:

public void ValidateEntity<T>(object dataSource)
{
   var validator = ValidationFactory.CreateValidator<T>();
   var results = validator.Validate(dataSource);
   if (results.Count > 0)
   {
      ValidationError.DisplayError(results.First().Message);
   }
}

Now instead of duplicating the functionality of validation with a

lot of functions that perform the same thing we have only

one function that perform the same thing but is more generic.

This is much better!

Summary

Lets sum up, to achieve code quality you shouldn’t repeat yourself.

Copy & Paste” helps to create code faster but it has the ability

to make your code very poor when it is being used without thinking.

Whenever you repeat some piece of code all over the place it’s a very big

sign for you that you need to refactor your code. One of the horrors of

a developer is to find all the duplications in a code base and change

some simple functionality.

So don’t repeat yourself!

DotNetKicks Image
Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published.

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>