![]() |
VOOZH | about |
DRY is simply an approach, or we can say, a different perspective to programmers. DRY stands for Don't Repeat Yourself. In Java, it means don’t write the same code repeatedly. Suppose you are having the same code at many places in your program, then it means you are not following the DRY approach; You are repeating the same code at different places. Hence, the solution is obtained using the DRY concept by placing the methods in place of all repeated codes and defining the code in one method. So by calling methods, we will reach the principle DRY. The DRY concept is very important to make the code better by reducing code redundancy and to encourage its reusability.
Applications:
Illustration 1:
Consider the scenario of the college student system. The college contains many departments. So each department has different people, but the college name is the same. So no need to specify the college name for each department by writing the code for the display of the college name.
Implementation: Without DRY approach
Example 1:
This is computer science IIT - Madras This is electronics IIT - Madras This is Information Technology IIT - Madras
Implementation: Applying the DRY principle
Example 1:
This is computer science IIT - Madras This is electronics IIT - Madras This is Information Technology IIT - Madras
Illustration 2:
Consider a program to calculate x3 and y5 for given inputs x and y.
Implementation : (Without DRY approach)
Output:
Enter the value of x: 3 Enter the value of y: 2 x raised to the power 3 = 27 y raised to the power 5 = 32
Explanation: In the above program, the logic to calculate the power of x and y is same for both the inputs. But this code is repeatedly used twice: once for x and once for y. So, to avoid this redundancy (repetition) of code, we will create a method to calculate power and place those repetitive lines of code into that method. And then we can call the method whenever and as many times we need to calculate the power.
Implementation: (After applying DRY approach)
Output:
Enter the value of x: 3 Enter the value of y: 2 x raised to 3 = 27 y raised to 5 = 32