Kotlin Code Smell 30 - Concrete Classes Subclassified

Kotlin Code Smell 30 - Concrete Classes Subclassified

Code Chaos to Composition Brilliance: A Transformation Tale

ยท

2 min read

Problem

Solution

  1. Subclasses should be specializations.
  2. Refactor Hierarchies.
  3. Favor Composition.
  4. Leaf classes should be concrete.
  5. 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 ๐Ÿ˜

Credits

Did you find this article valuable?

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

ย