Other day my Boss was reviewing the code written by me. He had a feedback, keep the code DRY. It was great feedback, and I thought why not to share with you that what does DRY mean?

DRY stands for Do not Repeat Yourself.

clip_image002

To understand it better let is consider below code snippet:

clip_image003

I am fetching a particular movie on basis of the id. As you notice this code is inside Details method. Next in another method Edit in the controller and I am doing the same fetching a particular movie on basis of the id as shown below:

clip_image004

As you clearly notice that I am repeating the code in the same class hence CODE IS NOT DRY in above scenario. The code should not be repeated and should be kept in repository class. We could have a function FindById() in MovieRepository class and both the methods will call FindById(). A common function to find the movie by id can be created as follows:

clip_image006

And then both methods of Controllers can use them as follows:

clip_image007

In the layered architecture approach DRY code is very essential for robust software development. I hope now you have better understanding of having code DRY and you will follow this approach.

Happy Coding.

Advertisements

5 thoughts on “Keep your code DRY

  1. Thanks for this example. But what about your DRY code for checking the the request parameter “id”?

  2. agree with the article. Because redundancy cause most of the problems when we revisit the code at the time or maintenance.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s