问题描述:

This question is in regards to proper and acceptable coding practice given the following scenario.

I have the following 2 Methods.

public TService GetDuplexClientChannel<T>(BindingType bindingType, EndpointAddress endPointAddress) where T : TService

{

.. Do work .. then ..

return InstanceOf(TService);

}

public TService GetDuplexClientChannel<T>(BindingType bindingType, string endPointAddress) where T : TService

{

// Call the above method and just return it.

return GetDuplexClientChannel<T>(bindingType, new EndpointAddress(endPointAddress);

}

In the first example I have Method A that does the work, and Method B which simply is an overload of A, but calls A to do the work.

I would like to know if this is an acceptable pattern , or should the code be repeated in the second method? What is the best practice for this.

I have looked at this link but it does not answer my question as to what is proper or not proper:

Better way to overload methods in C#

网友答案:

Yes, this is absolutely an acceptable pattern since in your case, your generic argument seems unrelated to the type of endpoint address.

It is seen in a variety of libraries and frameworks such as the .NET Framework (Console.Write) or the following Dapper source:

public static Task<IEnumerable<object>> QueryAsync(this IDbConnection cnn, 
    Type type, CommandDefinition command)
{
    return QueryAsync<object>(cnn, type, command);
}
网友答案:

Yes. That is entirely true way to overload methods in same class. Do not repeat code in the second method.

网友答案:

I would like to know if this is an acceptable pattern , or should the code be repeated in the second method? What is the best practice for this.

This pattern can be seen in many implementation and hence acceptable.

In order to make your code more maintainable, you shouldn't repeat it in any other methods.

Encapsulation is the best practice for similar cases.

相关阅读:
Top