patterncsharpMinor
Duplicate method call or add logic to set local variables as parameters?
Viewed 0 times
localmethodduplicatelogiccallvariablesparameterssetadd
Problem
This is a fairly trivial example of a question I come up to often. In the example below I tend to think that allowing duplication sometimes results in clearer code.
Does anyone agree/disagree on this point?
First way: an additional local variable is used so
Second way: No additional local variable but the call to
Does anyone agree/disagree on this point?
First way: an additional local variable is used so
method.Invoke is called just once on the last line. I think this has slightly more logic to decode than the second way.private static void Invoke(string[] args, MethodInfo method) where T : new()
{
T target = new T();
target.InvokeMethod("Initialize", errorIfMethodDoesNotExist: false, accessNonPublic: true);
string[] methodArgs = null;
if (args.Length > 1)
{
methodArgs = args.Skip(1).ToArray();
}
method.Invoke(target, methodArgs);
}Second way: No additional local variable but the call to
method.Invoke is duplcated in both branches of the if statement. I think this is clearer even though logic was duplicated.private static void Invoke(string[] args, MethodInfo method) where T : new()
{
T target = new T();
target.InvokeMethod("Initialize", errorIfMethodDoesNotExist: false, accessNonPublic: true);
if (args.Length > 1)
{
method.Invoke(target, args.Skip(1).ToArray());
}
else
{
method.Invoke(target, null);
}
}Solution
I think this would be even better, in this case.
private static void Invoke(string[] args, MethodInfo method) where T : new()
{
T target = new T();
target.InvokeMethod(
"Initialize", errorIfMethodDoesNotExist: false, accessNonPublic: true);
string[] methodArgs = args.Skip(1).ToArray();
method.Invoke(target, methodArgs);
}Skip() on an empty collection returns an empty collection.Code Snippets
private static void Invoke<T>(string[] args, MethodInfo method) where T : new()
{
T target = new T();
target.InvokeMethod(
"Initialize", errorIfMethodDoesNotExist: false, accessNonPublic: true);
string[] methodArgs = args.Skip(1).ToArray();
method.Invoke(target, methodArgs);
}Context
StackExchange Code Review Q#11753, answer score: 8
Revisions (0)
No revisions yet.