I have a method which has several "out" parameters. They are out as the value should be set to them inside the function. But in some cases compiler is not clever enough and it doesn't see parameter value is set in any execution path. That's why I have to set default values to out parameters at the beginning of the method. But as this method is part of interface with several implementations this initialization code is duplicated. And I don't like it.
What options do you see to solve this problem? One option I see is to开发者_开发问答 use ref instead of out. It isn't conceptually right as it doesn't guarantee parameter value will be set inside a method. But in fact it is the same (as I have default values setting at the beginning of the function, which means out in this case doesn't guarantee real values are set inside a method).
Any other options?
Personally, I try to avoid making a method that has "several" ref
or out
parameters.
As soon as you create a method that has more than a single ref
or out
parameter, personally, I feel it's time to consider refactoring to have it return a custom type (class
or struct
depending on the context) containing all of the data. This has many advantages, especially since it allows that type to handle its own validation for correctness in the construction of the type.
This is especially true if you have "multiple implementations" - as this should dramatically reduce the likelihood of errors as well as eliminating most of the duplicated code (since it can go into the new type).
Any method having several out parameters is a design smell to start with, to be honest. Do you really need these to be separate parameters, rather than one well-encapsulated return value? That would only be the case if the values were unrelated... in which case perhaps your method is doing too much in the first place.
Virtually the only place I regularly encounter out
parameters in the framework is TryParse
methods - and if Tuple<T1, T2>
had been available when they were designed, I suspect that would have been used in the first place. Alternatively, a ParseResult<T>
struct would be appropriate.
精彩评论