DEV Community

Cover image for Code Smell 43 - Concrete Classes Subclassified
Maxi Contieri
Maxi Contieri

Posted on • Edited on • Originally published at maximilianocontieri.com

3 1

Code Smell 43 - Concrete Classes Subclassified

Inheritance. Concrete classes. Reuse. A fantastic mix up.

Problems

Solutions

  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 extends ArrayList {
public void push(Object value) { … }
public Object pop() { … }
}
// 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 {
public abstract int size();
}
final class Stack extends Collection {
private contents[] ArrayList;
public Stack() {
contents = new long[maxSize];
}
public void push(Object value) { … }
public Object pop() { … }
public int size() {
return contents.size();
}
}
final class ArrayList extends Collection {
public int size() {
// ...
}
}

Detection

Overriding a concrete method is a clear smell. We can enforce these policies on most linters.

Abstract classes should have just a few concrete methods. We can check against a predefined threshold for offenders.

Tags

  • Composition

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 sub-classify an entity if it follows the relationships behaves like.

After sub-classing the parent class should be abstract.

Relations

More info

Wikipedia


Software is a gas; it expands to fill its container.

Nathan Myhrvold

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay