Hello Guys!
Before starting, I have a question, if someone says ten times the same words to us then what we will say, I think, we will say "Don't Repeat Yourself". The same thing we will learn in DRY principle.
We can do coding as we like but coding principles guide us to develop the best program in the long run. There are a number of principles and DRY is one of them.
It would be great if you know about SOLID principles, if don't then please read this article. It is 'What are SOLID principles?' in detail.
The DRY (Don't Repeat Yourself) principle is a design principle that promotes code reusability and maintainability by avoiding duplication of code. The DRY principle states that every piece of knowledge or logic in a software system should have a single, unambiguous, authoritative representation.
For example if we want to log our application's Exception then we can just use following code, but we have to add TRY and CATCH block code in all functions in the program, which is wrong according to the DRY Principle.
We have a problem in our code for error log and according to DRY Principle we should write a code in one place and we will track the error log in our program. We can try following:-
After adding message now let’s register global action filter in Global.asax. For that just open Global.asax file and add new function in it.
DRY principle benefits.
The DRY principle encourages developers to write code in a modular and organized manner, where common functionality is abstracted into reusable components or methods, and then referenced or invoked wherever needed, rather than being duplicated across multiple places in the codebase. By adhering to the DRY principle, developers can achieve the following benefits:
To adhere to the DRY principle in C#, developers can use techniques such as abstraction, encapsulation, inheritance, and composition to create reusable components, and utilize design patterns and best practices to avoid duplicating code. Additionally, using tools such as code analysis tools, automated refactoring tools, and code reviews can help identify and eliminate code duplication in a C# codebase.
Thanks, for reading the blog, I hope it helps you. Please share this link on your social media accounts so that others can read our valuable content. Share your queries with our expert team and get Free Expert Advice for Your Business today.
Hire me on Linkedin
My portfolio