Is there a significant mechanical difference between these faux simulations of default parameters?
C#4.0 introduced a very fancy and useful thing by allowing default parameters in methods. But C#3.0 doesn't. So if I want to simulate "default parameters", I have to create two of that method, one with those arguments and one without those arguments. There are two ways I could do this.
Version A - Call the other method
public string CutBetween(string str, string left, string right, bool inclusive)
{
return str.CutAfter(left, inclusive).CutBefore(right, inclusive);
}
public string CutBetween(string str, string left, string right)
{
return CutBetween(str, left, right, false);
}
Version B - Copy the method body
public string CutBetween(string str, string left, string right, bool inclusive)
{
return str.CutAfter(left, inclusive).CutBefore(right, inclusive);
}
public string CutBetween(string str, string left, string right)
{
return str.CutAfter(left, false).CutBefore(right, false);
}
开发者_开发知识库Is there any real difference between these? This isn't a question about optimization or resource usage or anything (though part of it is my general goal of remaining consistent), I don't even think there is any significant effect in picking one method or the other, but I find it wiser to ask about these things than perchance faultily assume.
The only real difference is that of maintenance; the second version is essentially a form of code duplication and you'll have more work to do (and perhaps more tests to run) if you need to change the implementation of these.
Otherwise, they're basically the same in every other respect - you'll have one extra method on the call stack in the first case, which won't have any noticeable effect on performance or resource usage (as you said, not an optimization problem).
Given that, when I need several overloads of the same method I tend to do what you did in the first example - have several overloaded methods all call the same "general" method.
There'll be no difference in behaviour, no - but version B isn't obviously just applying a default. You need to read the code carefully to verify that there aren't subtle differences. I think it's better to funnel any default values through one "master" method containing the real logic. That also makes it easier to change the logic later - you only have to do it in one place.
One difference is that if the CutAfter
or CutBefore
signature changes for any reason in the first version you need only update a single line whereas in the second version you have to update as many lines as you have methods.
精彩评论