DEV Community

Yonatan Karp-Rudin
Yonatan Karp-Rudin

Posted on • Originally published at yonatankarp.com on

Kotlin Code Smell 30 - Avoiding Concrete Class Subclassification Pitfalls

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

Enter fullscreen mode Exit fullscreen mode

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 { ... }
}

Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)