Skip to main content

Command Palette

Search for a command to run...

Kotlin Code Smell 30 - Concrete Classes Subclassified

Code Chaos to Composition Brilliance: A Transformation Tale

Updated
2 min read
Kotlin Code Smell 30 - Concrete Classes Subclassified

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

Kotlin Code Smells

Part 7 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 29 - Regular Expression Abusers

From Spaghetti Code to Readable Magic

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!