Kotlin Code Smell 30 - Concrete Classes Subclassified
Code Chaos to Composition Brilliance: A Transformation Tale

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
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 😁




