Yesterday I found myself "in the need" to add some useful extension method to my tool-belt pet-project.
This project contains most of what I feel it's useful for general purpose development, including code that I borrow from the Internet (after careful unit testing) as well as my own utilities.
As I was adding extension methods to the System.String class to perform a variety of actions I found myself implementing a common behavior in all of them. Basically I wanted all my extension methods to return null if the instance of the string was null (instead of throwing).
And since I am follower of the "just one place to return in my methods" (sue me), my methods were something like:
public static string ExtensionMethod(this string s, params object[] someOtherArguments) | |
{ | |
string result = null; | |
if (s!= null) | |
{ | |
// set result with whatever the extension mehod does | |
} | |
return result; | |
} |
I am also a well-known prosecutor of duplicated code and the vision of this all over my methods was bothering me big time. That reminded on a way to implement the Template Method pattern on a lower reusability level: methods instead of classes. Thus I plunged to create a simple templated method that contains the common behavior and leaves the specific behavior to be injected as a delegate. The result is as follows:
public static T NullOrAction<T>(T argument, Func<T> func) where T : class | |
{ | |
T result = null; | |
if (argument != null) | |
{ | |
result = func(); | |
} | |
return result; | |
} |
Which leaves the implementation of the extension methods in a more compact and, what's more important, less repetitive:
public static string NewExtensionMethod(this string s, params object[] someOtherArguments) | |
{ | |
return NullOrAction(s, () => "whatever result string might be"); | |
} |
Nice and easy and straight to my pain.