7
submitted 5 months ago by [email protected] to c/[email protected]

I came across this post (and more like it) claiming extensions to be a good, or at least different, solution for mapping DTO's.

Are they though? Aren't DTO's supposed to be pure data objects? I've always been taught to seperate my mappings in special mapping services or mapping libraries like MapStruct and ModelMapper for implementing the good practice of "seperation of concerns".

So what about extensions?

you are viewing a single comment's thread
view the rest of the comments
[-] [email protected] 2 points 5 months ago

Are they though? Aren’t DTO’s supposed to be pure data objects? [...] So what about extensions?

I'm not 100% familiar with Kotlin, but I think extension methods in Kotlin are the same as C#, basically syntactic sugar.

So you'd write an extension method like:

public static class ObjectExtension
{
    public static void DoSomething(this object input) { }
}

this being the keyword making it an extension method - and you can call that function on an object by doing object.DoSomething() - Yes. But underneath it's the same as doing ObjectExtension.DoSomething(object) (A static invocation to your ObjectExtension class and DoSomething method.

So on the surface it looks like you're injecting a new method into your DTO, and your DTO is not a pure data object anymore, but actually you're just creating an helper function that's statically invoked - that looks like you can call it "on the object" but actually you're not.

As for whether it's a good / common practice to create mappers like that in Kotlin, I don't really know. I do it often in C# though.

[-] [email protected] 1 points 5 months ago

I was suspecting something like that. I'll be looking into it a bit more.

I also notice some difference in what's considered "best practice" between Java and C#, so I'm not sure what's actually best practice haha. Probably somewhere in the middle, I suppose.

this post was submitted on 02 Apr 2024
7 points (100.0% liked)

Kotlin

662 readers
1 users here now

Kotlin is a statically typed programming language for the JVM, Android, JavaScript, and native.

Subreddit rules:

Resources:

founded 1 year ago
MODERATORS