Thursday, May 19, 2011

Try/Catch refactoring

Hi guys,
every now and then I enjoy learning and inventing some new tiny tricks and tips. They make my life easier and my code tidier. Today I would like to share some small refactoring, which I find neat and use all the time.

Original Code
Most probably, you often have to write repetitive code like the one below:
try
{
// Perform operations
}
catch (System.Exception ex)
{
// Log Exception
}

This is pretty common in windows applications/services. What I don't like is repetitive writing it.
So, how can we refactor it? We can review our list of Design Patterns and observe that what we can do is implement something like the Template method pattern. In C# we can use lambda expressions and anonymous methods to implement a lightweight version of a modification of this pattern.

Template method pattern modificatoin
Using the Template method pattern idea, we have to wrap our executing code with try/catch statements. We can create a class we can use to actually "inject" our operation. Something like this one:

public static class SafeCodeExecutor
{
public static T Execute<T>(Func<T> operation)
{
try
{
return operation();
}
catch (System.Exception ex)
{
// Log Exception
}
return default(T);
}
}

Now, we can freely use our SafeCodeExecutor throughout our project. Sample usage would be:
string designPatternName = SafeCodeExecutor.Execute<string>(() => 
{
return "Template method pattern";
});

Of course, you can free use a method inside the Execute<>.

You can build more Execute template methods which fit your needs - for instance taking Action with some parameters and etc (for instance:
public static void Execute<T>(Action<T> operation, T item)
). It's all up to you.

Hope you liked this little trick!

3 comments:

Павелъ Дончевъ said...

I was just going to ask what if you need to execute void method (requires Action) and saw that you think about it.

Way to go, Yosi!

Tihomir Atanasov said...

Great post, Yosko.

Small typo in "Excecute". Also would be nice to post the code for download ;)

cypressx said...

Hi Tisho :)

Thanks for the comment, you're correct about the typo and i've fixed it now. I'll try to upload the code snippets/files somewhere next time.

Really appreciated your feedback!