| Adam Vandenberg ( @ 2005-11-28 22:36:00 |
IanG on Tap: C# 3.0 - Extension Methods
One of the new C# 3.0 language features is 'extension methods'. The basic idea is that the set of methods available on an instance of a particular type is open to extension. In effect, we can add new methods to existing types.
This is similar to Categories in Objective-C (and related concepts in Smalltalk), and the ability to add methods to prototypes in Javascript, and various other mechanisms in various other languages.
But the problem in comparing features across langauges is that similar things are always different, due to differences in the exact semantics of the rest of the language. Quick! What's an object? Answer: whatever heck your particular language spec says it is.
But I didn't write this to talk about any of the above; I want to comment on this:
Developers new to .NET tend to be surprised that calling
ToUpperon a string doesn't convert it to upper case. And I think it's perfectly reasonably to be surprised.ToUpperlooks like an imperative operation. Its form actively conceals the fact that it's really a function in the strict functional programming sense - it's has no side effects, it merely takes an input expression returns a result based on that input expression without modifying the input in any way. The input expression is the implicitthisreference - the object on whichToUpperis invoked.I think this form would have been more honest, and less likely to mislead:
String.ToUpper(input)It's true that this would be more cumbersome, and would require more typing than what we've got today. But misleading code seems like a high price to pay for a little less typing - aren't we always being told that code will be read far more often than it is written? And even if you are convinced by the argument that a core class like
Stringis sufficiently widely used that (a) it's worth the savings in this case because it affects everyone, and (b) everyone knowsStringso it doesn't matter that it's a special case, it still seems like the wrong thing to do in the general case.
Holy heck GOSH what a bad idea. Cumbersomeness matters, even with IDEs and autocomplete and IntelliSense and what have you.
What language are these programmers coming from that this construct is confusing? I suspect the answer lies here: UCase Function (Visual Basic).
I suppose it helps to have used langauges before where (1) strings are immutable and (2) method call notation is the norm rather than the exception.