I have a a Polygon class. I'm adding several opera...
# announcements
h
I have a a Polygon class. I'm adding several operators and useful functions. Would you add these as methods in the class, or as extension functions? Not concerned with Java interop.
k
I make it an extension if it's a pure function. It makes it clearer to the reader that those functions don't modify internal state.
h
Ah yes I should mention, it's immutable.
k
yeah, I personally think I'd rather see
Copy code
data class Polygon(...)

operator fun Polygon.plus(other: Polygon): Polygon = ...
than
Copy code
data class Polygon(...) {
  operator fun plus(other: Polygon): Polygon = ...
}
and I feel like I see extensions preferred over members throughout the stdlib
s
I make functions that don’t require access to private members into extensions
h
Thanks "rules of thumb" like this is what I was looking for
s
There’s nothing specific in the coding conventions, so ultimately it comes down to personal preference. That’s just our respective philosophies :)
d
I prefer members because I dislike having to import extension functions. It leads to too many
*
imports. Imports can play a role for code readability, especially for other developers. Repositories where I can deduce the location of a symbol's declaration from imports at the top are helpful.
I would probably adopt extension functions more if importing the type they extend, imports all of them in that file.
g
I think that using extension functions is a clean way of putting the code at the right place. In the case of Polygon + Polygon, it makes sense to keep this function as a member function. I would use an operator extension function in the case of a bounded context.