In this article, We are going to study the “DRY” software design principle’s benefits and why this principle is helpful for us. Some best principles are KISS, SOLID, DRY/DIE, and YAGNI software perspective.
- KISS [Keep it simple, Stupid!]
- SOLID
- DRY/DIE [Don’t Repeat Yourself / Duplication is Evil]
- YAGNI [You aren’t gonna need it]
Let’s explore DRY [Don’t repeat yourself]
As we can read in heading DRY stands for don’t repeat yourself. Its also know as DIE which stands for Duplication is Evil. This principle simply means to reduce code and use reusable code everywhere. Don’t write lengthy methods, split code into smaller reusable pieces as max as possible and use existing code. As per Wikipedia “Every piece of knowledge must have a single, unambiguous, authoritative representation within a system“. Normally it’s similar to a class which we created like helpers or common to perform the same task with less affords.
As we can see in the above image we are printing names in each task, so instead of writing each line in each task, why we not should create a single method which does the print jobs and call from everywhere?.
There are some codes sample below for multiple solutions for the same thing, Now you need to decide which is best and which should be avoided?.
public void Task1() { var message = "My name is Faisal Pathan, I'm .NET Project Manager."; message = "Hello, Good Morning " + message; Console.WriteLine(message); } public void Task2() { var message = "This blogs written on TheCodehobs.com!"; message = "Hello, Good Morning " + message; Console.WriteLine(message); } public void Task3() { var message = "Example of DRY principle."; message = "Hello, Good Morning " + message; Console.WriteLine(message); }
public void Task1() { PrintJob("My name is Faisal Pathan, I'm .NET Project Manager."); } public void Task2() { PrintJob("This blogs written on TheCodehobs.com!"); } public void Task3() { PrintJob("Example of DRY principle."); } public void PrintJob(string message) { Console.WriteLine($"Hello, Good Morning {message}"); }
hope you guys found something useful. Please give your valuable feedback/comments/questions about this article. Please let me know how you like and understand this article and how I could improve it.