Are default parameters bad practice in OOP?

点点圈 提交于 2019-12-10 01:59:03

问题


Do default parameters for methods violate Encapsulation?

What was the rationale behind not providing default parameters in C#?


回答1:


I would take this as the "official" answer from Microsoft. However, default (and named) parameters will most definitely be available in C# 4.0.




回答2:


No, it doesn't affect encapsulation in any way. It simply is not often necessary. Often, creating an overload which takes fewer arguments is a more flexible and cleaner solution, so C#'s designer simply did not see a reason to add the complexity of default parameters to the language.

Adding "Another way to do the same thing" is always a tradeoff. In some cases it may be convenient. But the more syntax you make legal, the more complex the language becomes to learn, and the more you may wall yourself in, preventing future extension. (Perhaps they'd one day come up with another extension to the language, which uses a similar syntax. Then that'd be impossible to add, because it'd conflict with the feature they added earlier)




回答3:


As has been noted, default parameters were not a prioritized feature, but is likely to be added in C# 4.0. However, I believe there were excellent reasons not to include it earlier (in 4.0, as I've understood it, itäs mostly to support duck typing styles of programming where default parameters increases type compatibility).

I believe excessive parameter lists (certainly more than 4-5 distinct parameters) is a code smell. Default parameters are not evil in themselves, but risk encouraging poor design, delaying the refactoring into more objects.




回答4:


To your first question - no, it's exactly the same as providing multiple overloaded constructors. As for the second, I couldn't say.




回答5:


Default parameters will be included in C# 4.0

Some reading material about it:

click

click

It also seems that the author of this post will publish an article in the near future on the 'why' MS chooses to implement default params in C#




回答6:


Here is an answer why it's not provided in C# http://blogs.msdn.com/csharpfaq/archive/2004/03/07/85556.aspx




回答7:


One drawback with the default parameter implementation in C# 4.0 is that it creates a dependency on the parameters name. This already existed in VB, which could be one reason why they chose to implement it in 4.0.

Another drawback is that the default value depends on how you cast your object. You can read about it here: http://saftsack.fs.uni-bayreuth.de/~dun3/archives/optional-parameters-conclusion-treat-like-unsafe/216.html .



来源:https://stackoverflow.com/questions/624057/are-default-parameters-bad-practice-in-oop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!