Extension methods
Brian Goetz
brian.goetz at oracle.com
Wed Apr 24 16:42:08 UTC 2024
5. One of the answers from the first thread you provided (https://stackoverflow.com/a/29494337) states that omitting extension methods is a "philosophical choice", as API developers should define the API. I have to strongly disagree with that. Extension methods are NOT part of the API, they are EXTENSION to it. It does not breach encapsulation as it can't access any internal members of API classes.
You can convince yourself that you like it, but that doesn’t change the fact that it is a deliberate attempt to blur the boundary of the API. And again, you might think that is fine, but we do not. The members of String, and therefore the methods you can invoke through a String receiver, should be defined by the String class (and its supertypes.). Invoking a method on a receiver:
aString.encrypt()
where String has no method called encrypt(), is muddying the user’s view of what the API of String is. I get that you are willing to say “the API of String is the methods in String, plus any methods I care to create the illusion of belonging to String”, but that looks like monkey-patching to us. Worse, this “method call” might mean one thing in one context, and another thing in another context.
Extensions have to be imported explicitly (not the containing class), so they are explicitly mentioned in the imports list. Also, are utility methods also breaching this rule then? The only real difference I see is differences in notation, and extension methods are clearly much more concise.
Concision is not the goal of programming.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/amber-dev/attachments/20240424/f9d5efaf/attachment.htm>
More information about the amber-dev
mailing list