Search code examples
kotlincoding-style

Avoid repetition of same logic


I have the following data classes:

sealed class ExampleDto

object Type1ExampleDto : ExampleDto()

object Type2ExampleDto : ExampleDto()

data class Type3ExampleDto(val name: Int, val age: Int) : ExampleDto()

data class Type4ExampleDto(val name: Int, val age: Int) : ExampleDto()

data class Type5ExampleDto(val email: String) : ExampleDto()

data class Type6ExampleDto(val name: Int, val age: Int, val email: String) : ExampleDto()

In particular, Type3ExampleDto, Type4ExampleDto and Type6ExampleDto share some common fields but it's important for my business logic to distinguish between types (i.e. even if Type3ExampleDto and Type4ExampleDto are identical, I have to know if I'm in the type3 or type4 case).

In one of my method I have the following call:

when (type) {
            is Type3ExampleDto -> myMethod(type.vote, type.text)
            is Type4ExampleDto -> myMethod(type.vote, type.text)
            is Type6ExampleDto -> myMethod(type.vote, type.text)
            else -> null
        }

I find very ugly that I'm doing the same operation in all 3 cases and repeating the same line...

It makes sense to made Type3ExampleDto, Type4ExampleDto and Type6ExampleDto an implementation of some kind of interface just because only in this point I'm doing this kind of ugly repetition?

If all three dtos implement the following interface

interface MyInterface{
fun getVote() : Int
fun getText() : String

}

I can write:

if (type is MyInterface) {
    myMethod(type.getVote(), type.getText())
}

So, it's acceptable to create this interface just to solve this isolated repetition?

Thanks


Solution

  • Note you can do it much more cleanly like this:

    interface NameAndAgeDto {
        val name: Int
        val age: Int
    }
    
    data class Type3ExampleDto(override val name: Int, override val age: Int) : ExampleDto(), NameAndAgeDto
    
    if (type is NameAndAgeDto) {
        myMethod(type.name, type.age)
    }
    
    

    Whether it's "acceptable" is opinion. Looks fine to me.