https://kotlinlang.org logo
#getting-started
Title
# getting-started
u

ursus

11/27/2021, 1:30 AM
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

Stephan Schroeder

11/27/2021, 10:40 AM
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

ursus

11/27/2021, 2:56 PM
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

Daniel

11/27/2021, 8:57 PM
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

Jacob

11/28/2021, 1:10 AM
If every client of the class will need the function then IMO member is the way to go
g

gildor

11/28/2021, 8:52 AM
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
2 Views