Keep your code DRY

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.


To understand it better let is consider below code snippet:


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:


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:


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


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.

5 responses to “Keep your code DRY”

  1. Another gem of writing, DJ. You always inspire me.

  2. Thanks for sharing, I promise to my code DRY, henceforth 🙂

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

  4. 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: Logo

You are commenting using your 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 )

Connecting to %s

Create a website or blog at