Don’t Repeat Yourself
Today while I was
doing code review
I found myself
writing a new
instead of one
piece of code
that was repeating
itself in the
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
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.
Lets look at the code that I helped the developer to refactor:
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:
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!
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!