tags:

views:

526

answers:

7

Do default parameters for methods violate Encapsulation?

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

+1  A: 

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

anon
+3  A: 

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)

jalf
+9  A: 

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

Noldorin
+1  A: 

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#

Frederik Gheysels
+1  A: 

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

brzozow
A: 

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 .

JMD
+2  A: 

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.

Pontus Gagge