Introduction
I just wanna recall my favorite Open Closed Principle (OCP) in solid principles. It says that "Software entities should be open for extension, but closed for modification" .In simple words, any object can be allowed to extend the behavior instead of changing or modifying the behavior. This is the rule thumb for TDD applications that we should follow. The extension methods in .NET Core comes handy to fulfill the needs of adding functionality to the existing class without modifying anything.
What happens If we modify existing class?
Consider we designed a class for the specific purpose lets say "CALC" which is helpful for us to do ADD, SUB,MUL,DIV and all of its return types are integer. And also consider that we are utilizing this class all over the application whenever Calculation needs and completed the Test Cases. Now If we want our "CALC" class to return decimal instead of integer. This functionality could break all over the application. We need to reinvent the wheel of test cases which belongs to "CALC" class. This is exact problem where OCP principle plays a key role.
How to avoid disturbing existing class and add functionality to it?
Extending the functionalities in the existing class without disturbing it is cool. Because it won't break the functionality. Think about the class where you don't have code base and extending that class is an wonderful feature by .NET framework. In other words, we call it as extension methods. By using the extension methods we can extend the existing class without disturbing it.
Sample Code
Existing Calc Class
public class Calc
{
public int Add(int n1, int n2)
{
return n1 + n2;
}
}
Extended Calc Class using Extension Method
public static class ExtensionCalc
{
public static decimal ToDecimalAdd(this Calc calc, decimal n1, decimal n2)
{
return n1 + n2;
}
}
Client Class
static class Program
{
static void Main(string[] args)
{
Calc calc = new Calc();
var decimalvalue = calc.ToDecimalAdd(10m, 20m);
Console.WriteLine(decimalvalue);
}
}
Conclusion
I believe you might understand the power of the extension methods in ASP.NET Core where it won't disturb the existing class and modify the functionality by only extending it.
Comments
Post a Comment