Extension methods
Subrahmanyam V
vemana.github at gmail.com
Thu Apr 25 04:21:24 UTC 2024
>> On the other hand, an experience report from people doing different
kinds of work with Java is more likely to contain some new information.
I don't know if this is new information but in my practice, the most common
need for extension methods is with protobuf generated code. For example,
consider a protobuf that defines a Point type with x and y coordinates. The
generated code will have getters/setters/builders for x and y. But
sometimes, I wish to add derived properties, say Point.distanceFromOrigin()
{ return sqrt(x*x+y*y);} . Both Guava's AutoValue and Java Records enable
such 'derived' properties but there are no good options for generated code
to my knowledge. Extension methods can bridge that gap when changing
generated code is not practical.
That said, based on a little bit of experience with Groovy's metaclass
based additions, I am quite skeptical of extension methods for the purposes
of changing an API's shape. So, even if extension methods were available in
Java, I'd likely restrict usage to just the case above.
As a contrast to extension methods, one feature I'd use without restriction
(if it existed) is memoizing derived properties in records (like Guava's
AutoValue' Memoized annotation) particularly since memoization has
important performance implications. This contrast clarifies where my
personal "line" is - extension methods have global codebase-wide impact and
are easy to misuse, but property memoization is local impact with a
well-defined value proposition. So, yay to the latter but nay/meh to the
former.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/amber-dev/attachments/20240425/fe012880/attachment.htm>
More information about the amber-dev
mailing list