Hello there - Do You think is it idiomatic to use ...
# server
v
Hello there - Do You think is it idiomatic to use extension functions on data transfer objects in order to map to some other representation? I have doubts - as name suggests ‚extension function’ are for extending functionality of a class which already does something, while DTO should carry only data and no functions. On the other hand - extension function does not add methods to the extended object but are resolved statically - so DTO in its binary representation is still plain. It only lexically looks like you are messing with DTO. I would like to know your opinions.
d
Personally I don't mind using extensions because it cuts down on boilerplate. And you can scope the visibility which further helps.
👍 1
a
If it is your class then Don't use an extension function - you can put the convertor method inside it But if it is a class you do not own/control -- then yes
c
If you use some kind of architecture that requires you to put conversion stuff in another module, than I think it's completely fine to use extension functions. I use this for example to have API objects in the
api
module shared between client & server, then have all endpoints in
client
as extension functions on a
Client
class. The only times when you don't want to use extension functions is if you need inheritance or if you need interop with other languages. Every other time, just use what you feel is cleaner (for example, look at the source code of
String
in the standard library: 95% of it are extensions, same with
Sequence
)
z
FWIW, I did make mapper extension functions in my main app module to map data classes from other packages. Since my packages don’t know about other packages I had to centralize the mapping in my app module
v
Finally I decided to create extension functions on DTOs but those extension functions resides in Mapper class ( Mapper class is in different package than both - source and target DTO) for now I think it looks clean and consistent. Also using extension functions make it easier to read as there is no boilerplate. Its compact. Thank You all for your opinions.
d
Extension function seems in line with kotlin project lead Roman Elizarov’s explanation of extension oriented design since the mapping function isn’t truly part of the DTO https://elizarov.medium.com/extension-oriented-design-13f4f27deaee
v
Thanks for the article !
I think that is addressing my concerns - if or if it is not idiomatic to use extension functions in this particular context. Besides the fact - I would stick into extensions even though it is not idiomatic - It really cuts down on boilerplate and it just easier to read, and I cannot imagine any issues it introduces in this context. So... 🙂 thanks to all of You for helping.