Extensibility through Delegates

One of the key tenets of the SOLID principles used in object oriented design is the Open/Closed Principle. This states that software entities should be open for extension but closed for modification. This rather cryptic statement means that objects shouldn’t have to be changed every time requirements change. Clearly this is not always possible but objects can be made more tolerant to change through OO techniques such as inheritance and polymorphism. This is typically implemented using interfaces or abstract base classes that push responsibility out to concrete classes. Here is an excellent example.

However, this isn’t the only means to achieve this. C# is a rich language which provides multiple, complementary mechanisms to solve similar problems. Through delegates and lambdas, an alternative approach can be used. The following example demonstrates how a class can be extended without modification by allowing the caller to supply their own implementation.

internal class Helper
{
    internal static string UpdateString(string value)
    {
        return value.ToUpper();
    }
        
    internal static string UpdateString(Func<string> f)
    {
        return f();
    }
          
}

String s = "Hello";
Console.WriteLine(Helper.UpdateString(s));
Console.WriteLine(Helper.UpdateString(() => s.ToLower()));

Output

HELLO
hello

This simple example demonstrates how the Helper class can be offer an extensibility point via a method overload that accepts a delegate (in this case a Func<string>). The caller is able to override the default implementation which converts the string to upper case by providing its own implementation, in the form of a lambda expression.

For more on lambdas and delegates see my previous post on Linq.

Advertisements

Posted on November 3, 2012, in c#, delegates, lambdas and tagged , . Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: