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

윤동환

03/16/2023, 3:17 AM
When you use extension functions? my usecase: in my business, i have to create another domain class by Order entity class. So i write the code below.
Copy code
fun Order.createAnotherDomain() {
    // some validation logics...
    return AnotherDomain(
        // some parameters
    )
}
but i have another choice, companion object`s factory method…
Copy code
class AnotherDomain {
    companion object {
        fun from(order: Order) {
            // some validation logics...
               return AnotherDomain(
                   // some parameters
               )
        }
    }
}
so what is the appropriate way to create another domain class? i feel using the extension function looks like more readable and simple. i’m asking your opinion!
j

Josh Eldridge

03/16/2023, 4:25 AM
The question I'd ask here is what domain object needs to know about the other? Is AnotherDomain okay knowing about an Order? Then the second option works well, but if it's flipped and AnotherDomain shouldn't know about an Order then I may opt for the first. I'd probably say the first option, because the entity is okay knowing that the domain object exists, but you probably wouldn't want the domain object taking in an Entity object as its input. (Assuming the Entity object is something like a DB entity).
🙌 1
g

Goetz Markgraf

03/16/2023, 6:51 AM
I use extension functions sometime simply as a different way to pass a parameter – so that the function does neither belong to Order nor to AnotherDomain. It just gives the opportunity to use fluent coding style:
Copy code
returnsOrder()
  .createAnotherDomain()
  .doStuffWithOtherDomain()
  ...
In functional languages like Haskel or F# you would place this parameter last so that you can use a pipe operator:
Copy code
returnsOrder
|> createAnotherDomain
|> doStuffWithOtherDomain
Extension Functions can be used as a “Kotlin replacement” for this.
🙌 1
s

Stephan Schröder

03/16/2023, 1:17 PM
I also prefer the first way, coming from a similar point as Josh. AnotherDomain should concentrate on what it does, not where it comes from. So i normally put those converter-extension functions into a subpackages called "map".
👍 2
u

윤동환

03/25/2023, 4:08 AM
thanks for your answers, all of them is helpful for me!! The Order domain and the other domain are should not know each other, so i choose the first option.
3 Views