Keep Your Code DRY

The other day my boss was reviewing the code written by me. He had the feedback, keep the code DRY. It was great feedback and I thought I would share with you what DRY means.

DRY stands for Do Not Repeat Yourself.

dry

To understand it better let us consider the following code snippet:

cs code

I am fetching a specific movie on the basis of the id. As you can see the code is inside the Details method. Next in the other method Edit is in the controller and I am doing the same fetching of a specific movie on the basis of the id as shown below:

basis of the id

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

FindById

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

methods of Controllers

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

Happy Coding.

Up Next
    Ebook Download
    View all
    Learn
    View all