Whats the policy on extension functions on code I ...
# getting-started
u
Whats the policy on extension functions on code I own? Say I have
data class PhoneNumber(val normalized: String)
and I need to format it with spaces etc before rendering in UI Is this a member or extension function?
s
afaik there are different schools of thought on this. Classically it'd be a member function, but I like the idea of "only the core functionality should be in the class itself", so I'd probably use an extension function. (at least in my own projects since my colleagues at work have only recently started with Kotlin, so in order to have more harmonious code, I'd probably lower my code style a bit to classical)
1
oh, by the way, since you only have a single property you should probably use
@JvmInline value class PhoneNumber(val normalized: String)
, since this would avoid the wrapper overhead while retaining the type-safety. That only works on the JVM, of course. For other backends
data class
is fine. More info: https://kotlinlang.org/docs/inline-classes.html
u
Yes I also like the extension, however I think my key would be if formatting was in another module, i.e. you only need to format in ui, so ui includes :formatter module
d
This might be a usecase for a regular
PhoneNumberFormatter
class. This way the formatting is nicely encapsulated and you can mock it in unit tests if need be
1
When new to Kotlin some1 tends to write too many extension functions, since they are very cool. So best decide first if it is really a good case for an extension.
A good thought for extension / no extension is the following: Is (the possible extension) something general or domain specific? General lends itself more to extensions (like
isNotEmpty
) and domain specific lends itself more to member functions or other classes.
j
If every client of the class will need the function then IMO member is the way to go
g
I almost always use extensions for data classes, it doesn't matter general or domain specific, I try to avoid mixing data structure with business logic for it
And imo PhoneNumber it's a perfect example where you shouldn't use member function for such flexible and domain specific thing as number formatting, number formatting depends on language and region, it may depends on user's own preferences etc, so number formatting shouldn't be backed to PhoneNumber and instead you need a separate component/class which can work with PhoneNumber formatting