What are opinions on extensive use of extension fu...
# codereview
c
What are opinions on extensive use of extension functions/properties in codebases? I've recently started working on a new codebase and it feels like every file I look at has things like:
Copy code
private fun String.asDomainSpecificObject(): DomainSpecificObject = ...
I would prefer a function to handle such things that explicitly took a string. I thought the overwhelming view/opinion was that extension functions and properties were right when they extended the abstraction of the class that was being given an extension. Beyond initial confusion and my own opinion, is there any reason to avoid such use of extension functions/properties, or should I embrace it?
h
I hate that too, and some of my colleagues as well. Unfortunately, the official Kotlin Style Guide says
Use extension functions liberally.
And that leads to people doing everything in an extension. 😢
c
😞 kotlin style guide be damned, that's really unfortunate. Thanks Henning!
r
I’m mostly fine for this if it’s private and related to the responsibility of the class it’s in. It often makes for more readable/ fluent code, especially when nullables are involved:
Copy code
stringValue?.asDomainSpecificObject?.process()
vs
Copy code
stringValue?.let { asDomainSpecificObject(it) }?.process()
I think it’s something you get used to but definitely some codebases will use it more extensively than others
💯 1
c
>
Copy code
private fun String.asDomainSpecificObject(): DomainSpecificObject = ...
> I would prefer a function to handle such things that explicitly took a string. This is explicitly considered a bad idea by core library authors. For example, see
String.toInstant
that was deprecated in KotlinX.Datetime, and replaced by
Instant.parse(String)
It's a bad idea because extension functions should apply to all values of the type, not just specific ones that happen to be formatted like you want
💯 3
c
It's a bad idea because extension functions should apply to all values of the type, not just specific ones that happen to be formatted like you want (edited)
I really like this distinction!
c
I really like it as well, but
"123".toInt()
is a kind of weird case, because according to that rule it shouldn't exist, but it's sooo convenient
👍 1
c
at least
int
is part of the language though
👍 1
r
I’d say the biggest issue with
String.toInstant
is that it’s in the public/ global namespace (also as mentioned there, the fact that there was already a scoped version).
If I saw it as a private inside a Date parsing or mapping class I’d think nothing of it
3