I have many functions with different content but the parameters and try catch inside is almost similar. Is there anyway to wrap the function up so that can reduce redundant codes.
ResponseStatus GetPotatoList(GetPotatosRequest requestParam, out GetPotatosResponse response, out ResponseErrorType errorType)
{
ResponseStatus status = ResponseStatus.Fail;
response = new GetPotatosResponse();
//To Do
try
{
//To Do
status = ResponseStatus.Success;
}
catch(CustomException ex)
{
errorType = ResponseErrorType.CustomError;
}
catch(TimeoutException ex)
{
errorType = ResponseErrorType.Timeout;
}
catch(Exception ex)
{
errorType = ResponseErrorType.GeneralFailure;
}
return status;
}
You can pass an Action
to your method.
ResponseStatus GetPotatoList(Action action1, Action action2, GetPotatosRequest requestParam, out GetPotatosResponse response, out ResponseErrorType errorType)
{
ResponseStatus status = ResponseStatus.Fail;
response = new GetPotatosResponse();
action1();
try
{
action2();
status = ResponseStatus.Success;
}
catch(CustomException ex)
{
errorType = ResponseErrorType.CustomError;
}
catch(TimeoutException ex)
{
errorType = ResponseErrorType.Timeout;
}
catch(Exception ex)
{
errorType = ResponseErrorType.GeneralFailure;
}
return status;
}
Then use it:
var response = GetPotatoList(
() => doSomething(),
() => doSomethingElse(),
requestParam,
out response,
out errorType);
I needed to provide functionality before and after invoking an original method whose signature didn't vary much.
I used Func<..>...
public static Func<string, string> Hello = name => "hello " + name;
public static string Hello2(string name) => wrap(Hello)(name);
// This does NOT retain the name of the arg for hints in the IDE
public static Func<string, string> Hello3 = name => wrap(Hello)(name);
private static Func<string, T> wrap<T>(Func<string, T> orig)
{
return name => orig(name.ToUpper());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With