Generic and non-generic method with similar body

Viewed 605

I have a method called ExecuteAsyncServiceRequest with an overload, you'll notice that the body of the both methods are similar. I find myself wondering is there a more concise way of writing these methods? Specifically, to not have to repeat myself in the method body.

Thanks in advance!

    /// <summary>
    /// Executes an async service request which returns a response of type TResponse
    /// </summary>
    /// <param name="execute">The service request to execute</param>
    /// <param name="success">Callback when the service request is successful</param>
    /// <param name="failure">Callback when the service request fails</param>
    /// <typeparam name="TResponse">Type of the expected ServiceResult returned from the async request</typeparam>
    protected async void ExecuteAsyncServiceRequest<TResponse>(Func<Task<ServiceResult<TResponse>>> execute,
                                                            Action<TResponse> success,
                                                            Action<string> failure)
    {
        ServiceResult<TResponse> result = await execute();

        if (result.ResultCode == ServiceResult.ServiceResultCode.Failed)
            failure(result.FailureDetails);

        success(result.Response);    
    }

    /// <summary>
    /// Executes an async service request
    /// </summary>
    /// <param name="execute">The service request to execute</param>
    /// <param name="success">Callback when the service request is successful</param>
    /// <param name="failure">Callback when the service request fails</param>       
    protected async void ExecuteAsyncServiceRequest(Func<Task<ServiceResult>> execute,
                                                    Action success,
                                                    Action <string> failure)
    {
        ServiceResult result = await execute();

        if (result.ResultCode == ServiceResult.ServiceResultCode.Failed)
            failure(result.FailureDetails);

        success();
    }
1 Answers
Related