So, I'm quite new to Kotlin but not to software en...
# general-advice
j
So, I'm quite new to Kotlin but not to software engineering, and I've been having an internal discussion around extension methods, on one hand I found them extremely useful to add meaning and domain specific functionality to existing types, for example create a method for
Int
that validates wether the number is a valid national identity number, although I've been using
typealias Nin = Int
. On the other side my internal engineering brain is telling me that I'm adding unexpected behaviour to types I don't own . What is the general community consensus around it?
j
I think it’s ok to add extension methods whenever it’s not complex and does not depend on any context. but in your case… well, at some point either the rules for valid number can change, or the country you operate in… Too many unknowns, it might bite you if you go blindly with extension functions.
j
This is from Swift course on Stanford, here is where I first time learned about extensions.

https://youtu.be/VIEzNBPmQKk?list=PL3d_SFOiG7_8ofjyKzX6Nl1wZehbdiZC_&t=3260

I know it's diff language but the point is the same.
r
The great thing about them is that the extension function exists in the specific context where it makes sense. So you aren't adding your validation to
Int
, only to
Int
when in the context of a national identity number. You have to import the extension function explicitly for it to be visible.
I see three great reasons for them: 1. They allow chaining rather than nesting.
i.validate().toNi()
is much nicer to read and reason about than
toNi(validate(i))
2. They are brilliant for null handling. Instead of
val ni = if (i != null) toNi(i) else null
or
val ni = i?.let { toNi(i) }
it's much nicer to write
val ni = i?.toNi()
3. They allow subject verb object word ordering for those for whom it is natural
r
It’s important to treat them as adding utility (static) methods to objects rather than adding functionality to objects. This should help when deciding whether it makes sense to use an extension vs modify the object
For the example of modelling a domain as primitive + extensions this sounds like a really bad idea
One big issue is discoverability - it won’t be obvious to consumers which Int extensions actually make sense for the kind of Int you have (even with a typealias this can easily get lost)
k
For your use case, it sounds like you could use a value class and have the validation in the constructor.
j
Thanks everyone! I think I'll be using extension methods, now on... my hunch was that they are really useful if you want to have a domain rich code... and discoverability as @Robert Williams mentions was something I was concern of... I think that the
typealias
may help a little bit with it)... in regards of @Klitos Kyriacou message, the example was just an illustrative example just to make my question is not a real situation