DEV Community

Cover image for Code Smell 136 - Classes With just One Subclass
Maxi Contieri
Maxi Contieri

Posted on • Originally published at maximilianocontieri.com

3 2

Code Smell 136 - Classes With just One Subclass

Being generic and foreseeing the future is good (again).

TL;DR: Don't over-generalize

Problems

  • Speculative Design

  • Complexity

  • Over-Engineering

Solutions

  1. Remove the abstract class until you get more examples

Context

In the past, programmers told us to design for change.

Nowadays, We keep following the scientific method.

Whenever we find a duplication we remove it.

Not before.

Not with interfaces, not with classes.

Sample Code

Wrong

class Boss(object):
    def __init__(self, name):
        self.name = name 

class GoodBoss(Boss):
    def __init__(self, name):
        super().__init__(name)

# This is actually a very classification example
# Bosses should be immutable but can change their mood
# with constructive feedback
Enter fullscreen mode Exit fullscreen mode

Right

class Boss(object):
    def __init__(self, name):
        self.name = name  

# Bosses are concrete and can change mood
Enter fullscreen mode Exit fullscreen mode

Detection

[X] Automatic

This is very easy for our linters since they can trace this error at compile time.

Exceptions

Some frameworks create an abstract class as a placeholder to build our models over them.

Subclassifing should be never our first option.

A more elegant solution would be to declare an interface since it is less coupled.

Tags

  • Over Design

Relations

Conclusion

We need to wait for abstractions and not be creative and speculative.

Credits

Photo by Benjamin Davies on Unsplash


Writing a class without its contract would be similar to producing an engineering component (electrical circuit, VLSI (Very Large Scale Integration) chip, bridge, engine...) without a spec. No professional engineer would even consider the idea.

Bertrand Meyer


This article is part of the CodeSmell Series.

Dev Diairies image

User Feedback & The Pivot That Saved The Project ↪️

We’re following the journey of a dev team building on the Stellar Network as they go from hackathon idea to funded startup, testing their product in the real world and adapting as they go.

Watch full video 🎥

Top comments (0)

👋 Kindness is contagious

Discover fresh viewpoints in this insightful post, supported by our vibrant DEV Community. Every developer’s experience matters—add your thoughts and help us grow together.

A simple “thank you” can uplift the author and spark new discussions—leave yours below!

On DEV, knowledge-sharing connects us and drives innovation. Found this useful? A quick note of appreciation makes a real impact.

Okay