As someone that used to have to program in Java, moved over to Kotlin, but now have to work with Java again... I miss extension methods so much. Util classes feel so hacky, and are so ugly to use.
Specially for cases like streams, where you are invoking a chain of operations, and then have to store the temporary result in a variable, or have worse readability.
Or for quick and dirty debugging, with print statements, being able to put a println in the middle of any method call, just by adding a .also{println(it)} to the chain.
One pattern I see sometimes is to define a util class, but rather than having a bunch of static methods, you wrap the underlying object in a util wrapper that adds all of the utility methods. Unfortunately, Java also has no good way to delegate methods without simply redefining all of them, so it's by no means a perfect solution. (And it's not really worthwhile unless you've got a fluent API that returns the same object every time; otherwise you're wrapping for just one call, which is arguably noisier.)
The most straightforward solution to this is the one that D employs, whereby A(B) is syntactic sugar for A.B() if the former is not otherwise valid.
Re:Rails is not written in Ruby
by dragonwriter on Friday February 04, 2022 @06:36PM
(#30215087)
> The most straightforward solution to this is the one that D employs, whereby A(B) is syntactic sugar for A.B() if the former is not otherwise valid.
Isn't the D solution actually that:
A.B(...)
is syntactic sugar for: B(A,...)
if A.B() is not specifically defined.(Yours both flips the elements and reverse the direction of sugaring, as I understand it.)
Some languages (like C# and Rust) support extension methods, so you can use method-style to invoke separately-defined procedures. But in other languages, method-style APIs become an inextensible privileged zone, and I personally prefer to minimize the number of inherent methods as much as possible. By preferring direct-style invocations, I avoid the temptation to stick a useful method on the class itself "for convenience".