问题
I was looking at a former colleagues post. He quoted something from an article
"In Clean Code Bob Martin disparages output arguments, saying “In general output arguments should be avoided.”
My current code base is C#. I am working in a rather large application. It was written primarily in procedural style often breaking SOLID principles. When I have the opportunity I often will break some of the methods that violate single responsibility principle into separate methods. At times I'll create methods with a couple of output parameters as in the following.
var value1 int;
var value2 int;
DoSomeWork(out value1, out value2);
I prefer this over creating a special types which would never be reused anyways if a type were created. Is this acceptable or is there a better approach?
回答1:
It's correct that output parameters should generally be avoided. When possible (and reasonable) it's better to just return the result. Using output variables gives you a process of Prepare - Call - Handle that is more complex than it has to be.
You don't always have to create a new type to use for return value. There are types in the framework that you can use as long as you don't need a specific name for the components in the return value:
public Tuple<int, int> CalculateMinMax()
This is of couse only good if the meaning of the return value is obvious. In the example above the two values would be expected to be the minimum and maximum that was calculated, in that order.
If the return value is more complex, you are better off creating a type for it. If it's that complex, then using output variables for it will not make for simple code either.
回答2:
TL:DR; If you're writing high level code, you shouldn't use output parameters.
There are good reasons to use output parameters in some cases. For example, int.TryParse
is a perfect example of a function which uses output parameters to return a second value.
One could argue that the reason for that is efficiency, since it doesn't need to construct a wrapper object just to parse an integer.
On the other hand, if you write high level code, you should probably use a class or a struct that wraps those two values. If all you're doing is returning two values, you can use Tuple
or write your own struct
that will have almost no overhead. I'm saying almost no overhead, since all object creation will have some overhead.
If you're writing a tight loop that needs to run as fast as possible, for example a parser of some sort, you might benefit more from using the output parameters, which won't have to allocate any excessive objects.
来源:https://stackoverflow.com/questions/27204827/clean-code-are-output-parameters-bad