Principle#0(DRY)

At first i want to talk about why we need design principles??
The answer will be:
A design principle is a basic tool or techique that can be applied to desiging
or writing code to make it more (maintainable,flexible and extensible)

Let see the first principle

Principle#0: The Dont Repeat Yourself Principle
This means avoiding duplicate code by abstracting out things that are common and placing those things in a single location.

Another meaning :–>If there is any common code between any 2 functions or between any 2 classes we should put it in one place only then reference to it.

*The importance of this principle
1- Makes you sure that you are avoid duplicating your code so you also avoid duplicating in your requirements
2- useful through maintenance phase as when you like to change any part of your code
,you will change it in a single place.

 

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

Enjoy 😀

Posted in OOD

Leave a comment