问题
I ran the VS 2008 code analysis tool against an object I created and received the following suggestion ...
Warning 147 CA1021 : Microsoft.Design : Consider a design that does not require that 'returnValue' be an out parameter.
I find "out" parameters rather useful and didn't realize that they were considered as a frowned upon design practice. I wanted to know if someone could shed some light on the reason that I received this Warning? If it is bad practice? why? and what would be good practice?
I appreciate any advice.
回答1:
Every Code Analysis warning has associated documentation that you can access by highligting the warning and pressing F1. You can also right-click on the item to get help.
In any case, here's the documentation that explains that particular warning.
I would say that there are a few cases where out parameters are still a good choice - particularly when it comes to the TryParse coding idiom, because it's such a well-established way of doing things that most people are supposed to understand it
In general use, however, there are better, more object-oriented solutions to multiple return values.
回答2:
I once ran myself code analysis on my project. Also I did get many insightful suggestions, I very briefly turned this off. Many of the suggestions are of a religious nature, you can do it this way or the other, a matter of style and not a bad practice.
To your situation. If you only have one return parameter, then return it back out of the function.
If you also have a return code that occupies the return place, consider using exceptions to inform the caller code of operation errors.
If you have many parameters to return that are closely related to each other, make a class/structure to hold them together and return it as a pack.
回答3:
Many of the code analysis warnings seem to me to be relevant to writing API code that 3rd parties will use. Your rule with 'out' parameters is a classic case: part of the reason not to use them is because a lot of other programmers won't know about them.
If they don't match what you are writing, then switch off code analysis rules that don't suit you. Personally I tend to switch off naming, portability, and interoperability rules as they are not relevant for the type of code that I write.
回答4:
I have turned this specific warning off in most of my projects. Since, I know that, when I use an out parameter, I have a good reason to do so, since I try to avoid them altogether.
I could imagine though that, when working with multiple persons on a project, you might want to have this warning turned on if you want to do some code reviews ...
来源:https://stackoverflow.com/questions/1404878/code-analysis-comes-back-with-suggestion-about-not-using-out-parameters