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.

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.

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 comment

Create a website or blog at WordPress.com