DRY principle in programming

DRY principle (Don’t Repeat Yourself) is a principle that every programmer needs to understand and follow. In this tutorial, let’s learn about this principle.

The DRY principle shows that if we are trying to write the same code in different places, instead of copying and pasting that code, we put that code into our own method and then call this method from the places we need to call.

Applying this principle, our code will be clearer and easier to maintain.

I will make an example for you to understand better!

Suppose I have an object called Calculator, this object has two main tasks: sum and averaging the sum of two numbers a and b.

If you do not apply DRY, the code will be as follows:

Now, if I want to print the sum of two numbers each time I perform two calculations in the Calculator object, I have to revise these two methods as follows:

As you can see, whenever you want to edit something related to the same code, we have to edit each one.

To overcome this, we will apply the DRY principle as follows:

And now to print the sum of two numbers, we just need to modify the total() method:

Add Comment