Skip to main content

Command Palette

Search for a command to run...

Kotlin Code Smell 16 - Instance Type Checking for Polymorphism

Ditch the Type Checks: Let Your Code Dance to Polymorphism's Tune

Published
2 min read
Kotlin Code Smell 16 - Instance Type Checking for Polymorphism
Y

I've started to work as a software engineer at 2014, however, I started to write code at high-school.

My first language was Assembly, but still, I fall in love with the possibilities to make the computer to do as you wish, shortly after that I started to write in C.

Later on I studied a practical engineering in electricity, and during this time discovered that I preferred much more writing code than design electrical components.

As a result of this understanding I decided to switch and study bachelor degree in computer science in Reichman university, where the focus was of the Java language.

Today I'm working at SumUp using Kotlin, SpringBoot & Micronaut, Cassandra and Kafka

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

Problems

  • Coupling: Objects are tightly coupled due to instance type checking.

  • Metamodel interference: The use of instance type checking interferes with the metamodel.

  • IFs: Excessive use of if statements.

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 objects with accidental decisions and violates bijection since no such control exists in the real world. It is a code smell that indicates our models are not good enough.

Credits

Kotlin Code Smells

Part 21 of 36

In this series, we will see several symptoms and situations that make us doubt the quality of our development. We will present possible solutions. Most are just clues. They are no hard rules.

Up next

Kotlin Code Smell 15 - Helper Classes

Goodbye Helpers, Hello Clean Code!

More from this blog

Yonatan Karp-Rudin | kotlin for backend developer skills | java for backend developer skills | SpringBoot | Tutorials

57 posts

Experienced Senior Software Engineer passionate about functional programming & Kotlin. Excels in app development, optimization, and team collaboration. Let's create something amazing!