Only a little trick to remove duplication


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:

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:

Which leaves the implementation of the extension methods in a more compact and, what's more important, less repetitive:

Nice and easy and straight to my pain.

share class