top of page
Writer's pictureamol ankit

Mastering the Art of Code Efficiency: Embrace the DRY Principle

Updated: Nov 8, 2023


Coding

Dry stands for Don't repeat yourself. The whole purpose of this principle is to create a habit of not repeating the same logic at multiple places in your codebase.

This principle was first popularised in the book "The Pragmatic Programmer" and it emphasised not repeating the code in your codebase.


Example of DRY Principle

Creating a separate method/function (depending on the choice of your programming language) for any logic which will be used more than once is the crux of the DRY principle.

Below is a code sample where the DRY principle is not implemented, The reason is that the same logic to convert the value from Fahrenheit to Celsius is repeated.


double zeroDegreeFah = 0;
double hundredDegreeFah = 100;

double celsiusValueOne = (zeroDegreeFah - 32 ) * 5 / 9;
double celsiusValueTwo = (hundredDegreeFah - 32 ) * 5 / 9;

Now let's refactor the code to make it compliant with the DRY principle.

double zeroDegreeFah = 0;
double hundredDegreeFah = 100;

double celsiusValueOne = FahrenheitToCelsius(zeroDegreeFah);
double celsiusValueTwo = FahrenheitToCelsius(hundredDegreeFah);

public double FahrenheitToCelsius(decimal inputInFahrenhit)
{
    return (inputInFahrenhit - 32 ) * 5 / 9;
}

As you can see in the above code snippet the logic to convert the temperature from Fahrenheit to Celsius is extracted into a separate method so as to avoid repeating the logic.


Advantage

  • Easy to maintain codebase.

  • Easy to read as there is no redundancy in the code.


Caution while DRY-ing your code

As it is said that excess of anything is bad, we also have to make sure that we are not overdoing this in our codebase which can create unnecessary abstraction in code and hence increase the complexity of the code rather than making it simple.


Premature Refactoring: One of the common mispractices is to create or extract a method where it is not needed.


Conclusion

In conclusion, the DRY (Don't Repeat Yourself) principle is a fundamental concept in software development that encourages code reusability and maintainability. By adhering to this principle, developers can reduce redundancy, minimize errors, and enhance the readability of their code. This not only makes the codebase easier to maintain but also promotes efficient collaboration among team members. The DRY principle is not just a coding guideline; it's a mindset that empowers developers to create more robust and scalable software systems. So, whether you're a novice programmer or a seasoned pro, remember that embracing the DRY principle is a crucial step towards writing cleaner, more efficient code and building software that stands the test of time.



Other Related Links





7,754 views0 comments

댓글

별점 5점 중 0점을 주었습니다.
등록된 평점 없음

평점 추가
bottom of page