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 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<T>(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<T>(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);
}
}