Kotlin Code Smell 30 - Avoiding Concrete Class Subclassification Pitfalls
Yonatan Karp-Rudin
Posted on August 18, 2023
Problem
- Bad Models
- Coupling
- Liskov Substitution Violation
- Method overriding
- Mapper fault
Solution
- Subclasses should be specializations.
- Refactor Hierarchies.
- Favor Composition.
- Leaf classes should be concrete.
- Not-leaf classes should be abstract.
Sample Code
Wrong
class Stack<T> : ArrayList<T>() {
fun push(value: T) { }
fun pop(): T { }
}
// Stack does not behave Like an ArrayList
// besides pop, push, top it also implements (or overrides) get, set,
// add, remove and clear stack elements can be arbitrary accessed
// both classes are concrete
Right
abstract class Collection {
abstract fun size(): Int
}
class Stack<out T> : Collection() {
private val contents = ArrayList<T>()
fun push(value: Any) { ... }
fun pop(): Any? { ... }
override fun size() = contents.size
}
class ArrayList : Collection() {
override fun size(): Int { ... }
}
Conclusion
Accidental sub-classification is the first obvious advantage for junior developers.
More mature ones find composition opportunities instead.
Composition is dynamic, multiple, pluggable, more testable, more maintainable, and less coupled than inheritance.
Only subclassify an entity if it follows the relationship behaves like.
After subclassing, the parent class should be abstract.
Java made this mistake, and they're regretting it until now. Let's do better than Java 😁
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
Posted on August 18, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.