I find myself having a lot of this in different methods in my code:
try
{
runABunchOfMethods();
}
catch (Exception ex)
{
logger.Log(ex);
}
What about creating this:
public static class Executor
{
private static ILogger logger;
public delegate void ExecuteThis();
static Executor()
{
// logger = ...GetLoggerFromIoC();
}
public static void Execute<T>(ExecuteThis executeThis)
where T : Exception
{
try
{
executeThis();
}
catch (T ex)
{
// Some kind of Exception Handling Strategy...
logger.Log(ex);
// throw;
}
}
}
And just using it like this:
private void RunSomething()
{
Method1(someClassVar);
Method2(someOtherClassVar);
}
…
Executor.Execute<ApplicationException>(RunSomething);
Are there any downsides to this approach? (You could add Executor-methods and delegates when you want a finally and use generics for the type of Exeception you want to catch…)
Edit: Sorry for being unclear – what I was really after was some input on the general idea of trying to move the execution of code from the class in question to a more generalized class that does this. I just did a quick mock-up of a solution but in real life you would naturally use things such as exception handling strategies, abstract execution base classes with more specialized execution classes for a specific layer/part of the system. I generally create one method with the try…/runABunchOfMethods-part (this does the exception handling, with specialized exceptions) that calls the runABunchOfMethods that in turn execute a limited set of other methods “clean code” style.
I’ll buy the obfuscation argument on some levels but if the whole solution/architecture takes this proposed approach a new programmer should be able to understand the pattern.
I’ve edited the Executor to include a generic T to allow the calling code to specify the exeception just to show how to handle a specialized exeception. In other cases you might have a bunch of catch:es depending on the what you want to do but those are special cases in the concrete subclasses I was talking about.
If you want to keep your objects clean, you could consider using an AOP framework like PostSharp. Then your logging of exceptions (for example) can all be handled in one place if you so desire.
EDIT:
It is possible to remove the try / catch blocks using postsharp – here is an example common exception handler that could be created in PostSharp:
If you apply this attribute to a class, any exceptions that any methods in that class throw will then be directed through the above code.