How do you name factory functions? :one: Simple ...
# codingconventions
m
How do you name factory functions? 1️⃣ Simple function name
Copy code
fun interface SomeLongTypeNameFactory {
   fun create(): SomeLongTypeName
}
Con: Causes conflict if a class implements multiple factories. 2️⃣ Function name explicitly mentions type
Copy code
fun interface SomeLongTypeNameFactory {
   fun createSomeLongTypeName(): SomeLongTypeName
}
Con: Long & repetitive. 3️⃣ Other convention (add comment)
1️⃣ 5
3️⃣ 1
2️⃣ 2
m
I’d say that the expectation in Kotlin would be a camel case function name like
mapOf()
or
mutableListOf()
. I haven’t yet seen factory interfaces … I guess for those I would opt for
createX()
, and make
X
as short as possible.
👍 1
m
Factory functions create concrete implementations. You cannot change implementation, e.g. for unit testing or dependency injection. For that you need an interface.
m
Sure, I’m aware of the pattern. I just haven’t seen it in a long time. I think it’s preferable to use dependency injection. When you define your classes consuming all the dependencies in the constructor or as function parameters, you can always mock them easily. And if you inject them using interfaces, you can also easily swap the implementations.
That isn’t to say that there are no valid use cases for factories anymore 🙂
m
I do need and use factories for unit testing & DI. That’s why I’m writing them at the moment and have this convention question 😄
Although I may rename them to generators. They create/generate IDs.
Problem remains though. Same for providers, generators, etc.
d
You could always use the invoke operator if you have enough context (like making it seem like you're calling a constructor) I've seen that pattern quite a bit for factories, but I'm not sure how to make that replaceable in testing...
m
I used that trick with the invoke operator - it’s neat because you can get rid of the combo variableName.function and simply invoke the variable. It feels like a hack though, and surprising for the caller. Plus it only works for single function factories.
m
operator fun invoke()
would also be variant 1️⃣ along with its potential for conflict. Just with a different function name.
d
Yeah, it depends on the context it's used in... if there's enough context around it, it's sometimes the nicest to use.