Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic Function wrapper

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;
}
like image 391
Z.V Avatar asked Dec 19 '22 10:12

Z.V


2 Answers

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);
like image 111
Kilazur Avatar answered Dec 24 '22 02:12

Kilazur


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());
    } 
like image 42
Peter L Avatar answered Dec 24 '22 00:12

Peter L