I want to DRY my source code. Let’s say I had some of these functions which mainly differ in one line – how could I achieve that??
public Result foo (int x, int y, int z){
Log.Say("Foo started!"); <<< DIFFERENCE
DoSomeMagic();
try {
result = controller.foo(x, y, z); <<< DIFFERENCE
} catch (Exception){
Log.Say("Something went terribly wrong");
}
return result;
}
public Result bar (Person a, string whatever){
Log.Say("Bar started!"); <<< DIFFERENCE
DoSomeMagic();
try {
result = controller.bar(a, whatever); <<< DIFFERENCE
} catch (Exception) {
Log.Say("Something went terribly wrong");
}
return result;
}
It’s driving me nuts, because it can’t be that difficult? I’m too confused by the various approaches by now; so far I tried to do it with a delegates,
Func, Lambda expressions, anonymous functions, but I just can’t get it to work (guess I need a break).
public Result handler (Func callbackMethodWithArgs) {
Result result = null;
Log.Say(method + " started!");
DoSomeMagic();
try {
result = invoke(callbackMethodWithArgs) as Result;
} catch (Exception) {
Log.Say("Something went terribly wrong");
}
return result;
}
public Result foo (int x, int y, int z) {
return handler(controller.foo(x, y, z));
}
public Result bar (Person a, string whatever) {
return handler(controller.bar(a, whatever);
}
As an addition it would be really great to have the possibility to use an anonymous function, like
public Result foo (int x, int y, int z) {
return handler(delegate () {
controller.foo(x, y, z));
doSomethingOther();
});
}
Any suggestions?? Thanks! (I read many question on similiar topics, but I didn’t find anything what solved the problem for me – so I assume it’s probably a duplicate – if so, I’m sorry)
You can do this using
Func<Result>:And then at the call sites turn them into delegates:
Note: If you’re on .NET 2.0 you can create the
Func<_>delegate manually before using the code above:As an aside, hiding exceptions in this way is not a great idea. You’re returning null and just logging an exception, as opposed to rethrowing it and letting calling code decide what to do. Could work for your use case, but is generally a red flag.