Kotlin Code Smell 31 - Not Polymorphic

yonatankarp

Yonatan Karp-Rudin

Posted on August 21, 2023

Kotlin Code Smell 31 - Not Polymorphic

Problems

  • Missed Polymorphism
  • Coupling
  • IFs / Type check Polluting.
  • Names are coupled to types.

Solutions

  1. Rename methods after what they do.
  2. Favor polymorphism.

Sample Code

Wrong

class Array {
    fun arraySort() { ... }
}

class List {
    fun listSort() { ... }
}

class Set {
    fun setSort() { ... }
}

Enter fullscreen mode Exit fullscreen mode

Right

interface Sortable {
    fun sort()
}

class Array : Sortable {
    override fun sort() { ... }
}

class List : Sortable {
    override fun sort() { ... }
}

class Set : Sortable {
    override fun sort() { ... }
}

Enter fullscreen mode Exit fullscreen mode

Conclusion

Naming is very important. We need to name concepts after what they do, not after accidental types.


I hope you enjoyed this journey and learned something new. If you want to stay updated with my latest thoughts and ideas, feel free to register for my newsletter. You can also find me on LinkedIn or Twitter. Let's stay connected and keep the conversation going!


Credits

💖 💪 🙅 🚩
yonatankarp
Yonatan Karp-Rudin

Posted on August 21, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related