What's the "best" alternative to writing static ut...
# getting-started
c
What's the "best" alternative to writing static utility functions in java? I know kotlin has companion objects, named companion objects, object classes, top level functions and extension functions... but a majority of the time, would you say that your XYZUtil.java turns into a whole bunch of kotlin extension functions?
r
As always, it depends. If there was one universally "best" way, Kotlin would have any of the others. "Majority of the time" is often a terrible metric for these kinds of things as they are highly context sensitive.
But that's just my $0.02
n
false, extension methods are the best alternative 🙃
🧌 2
while I agree there is no "best", extension methods are excellent for what would otherwise be static utils. or even just regular methods that get thrown into the class because it's convenient
r
@elizarov wrote an excellent article a while back about how extensions can provide an interesting paradigm shift. I'd highly recommend reading it if you haven't: https://medium.com/@elizarov/extension-oriented-design-13f4f27deaee
c
I have not. Thank you.
t
I agree with using extension functions (in most cases 😉). In my experience, those static utility class functions usually have one major purpose: providing functionality you wished was already present in the class, but it's missing so you implement it yourself. Extension functions are perfect for "pretending" the class has this functionality. On the technical side: When compiling for JVM, top-level-(extension-)functions will be compiled to simple static functions with an added parameter for the receiver. In some cases you need utility functions that don't make sense as extensions but would be better implemented as normal functions. Here - again - it depends, but esp. if the input parameters are something common like primitive types, I prefer putting functions like that into an
object
to provide more context on the call side.
👍 1