What is bad practice when using out parameters? [c

2019-01-16 16:07发布

Are there any principles to keep in mind when using out parameters? Or can I look at them as just a good way to let a method return multiple values?

What did the language designers have in mind when they were specifying the out parameter?

Edit after some thought:

As i'm thinking about it now, I would be inclined to say that excessive use of out parameters could be indicitive of a code-smell. If a method needs to return instances of more than 1 specific type it implies that the method has more than 1 concern, which is a violation of SRP.

10条回答
孤傲高冷的网名
2楼-- · 2019-01-16 16:27

Using out parameters at all is generally bad practice. It typically indicates a method that is doing more than one well defined thing. The only time I recommend using them is for Interop scenarios where they are sometimes necessary because of the signature of the API.

查看更多
男人必须洒脱
3楼-- · 2019-01-16 16:31

The class design tools specifically say to "Avoid out parameters", with a long discussion for the rationale.

Unless there is a good reason to use an out parameter for a method, it is typically better to make a custom class or struct to hold your results. Using out parameters reduces the usability of an API.

查看更多
走好不送
4楼-- · 2019-01-16 16:36

I often use nullable types when returning value types plus an indicator of success rather than returning a bool and using an out parameter for the value type. I even wrap the TryParse method so that it returns a nullable.

Out parameters are bad also because they must use local variables or fields. You can't easily refactor your code to use properties.

It's almost always best to create a custom class/struct, use tuples or nullable types.

查看更多
叛逆
5楼-- · 2019-01-16 16:38

While out parameters have their use, before using one you should stop and think if you really need it. You may be able to come up with a simpler, cleaner implementation that does not require out.

why-are-out-parameters-in-net-a-bad-idea has more information.

查看更多
登录 后发表回答