Yonatan Karp-Rudin
Yonatan Karp-Rudin

Follow

Yonatan Karp-Rudin

Follow
Kotlin Code Smell 016 - Instance Type Checking For Polymorphism

Kotlin Code Smell 016 - Instance Type Checking For Polymorphism

Do you check who are you talking to?

Yonatan Karp-Rudin's photo
Yonatan Karp-Rudin
ยทDec 23, 2022ยท

2 min read

Play this article

Table of contents

  • Problems
  • Solutions
  • Sample Code
  • Conclusion
  • Credits

TL;DR: Trust your collaborators. Don't check who they are. Ask them to do it instead.

Problems

Solutions

Sample Code

Wrong

class Rabbit {
    fun run() = println("I'm running! ๐Ÿƒโ€")
}

class Seagull {
    fun fly() = println("I'm flying! โœˆ๏ธ")
}

fun move(animal: Any) =
    when(animal) {
        is Rabbit -> animal.run()
        is Seagull -> animal.fly()
        else -> throw IllegalArgumentException("Unknown animal type")
    }


fun main() {
    val bunny = Rabbit()
    val livingstone = Seagull()

    move(bunny)
    move(livingstone)
}

Right

abstract class Animal {
    abstract fun move()
}

class Rabbit : Animal() {
    override fun move() = println("I'm running! ๐Ÿƒโ€")
}

class Seagull : Animal() {
    override fun move() = println("I'm flying! โœˆ๏ธ")
}

fun main() {
    val bunny = Rabbit()
    val livingstone = Seagull()

    bunny.move()
    livingstone.move()
}

Conclusion

Testing for a class type couples the objects with accidental decisions and violates bijection since no such control exists in the real world. It is a smell our models are not good enough.

Credits

Did you find this article valuable?

Support Yonatan Karp-Rudin by becoming a sponsor. Any amount is appreciated!

Learn more about Hashnode Sponsors
ย 
Share this