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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
package com.huongdanjava; public class Calculator { public int total(int a, int b) { return a + b; } public double average(int a, int b) { int sum = a + b; return sum / 2; } } |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
package com.huongdanjava; public class Calculator { public int total(int a, int b) { int sum = a + b; System.out.println("Total=" + sum); return sum; } public double average(int a, int b) { int sum = a + b; System.out.println("Total=" + sum); return sum / 2; } } |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
package com.huongdanjava; public class Calculator { public int total(int a, int b) { return a + b; } public double average(int a, int b) { int sum = total(a, b); return sum / 2; } } |
And now to print the sum of two numbers, we just need to modify the total() method:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
package com.huongdanjava; public class Calculator { public int total(int a, int b) { int sum = a + b; System.out.println("Total=" + sum); return sum; } public double average(int a, int b) { int sum = total(a, b); return sum / 2; } } |