Code Smell 161 - Abstract/Final/Undefined Classes

Photo by William Bossen on Unsplash

Code Smell 161 - Abstract/Final/Undefined Classes

Your classes are abstract, final, or undefined

Maxi Contieri
·Sep 2, 2022·

2 min read

Subscribe to my newsletter and never miss my upcoming articles

Play this article

Table of contents

  • Problems
  • Solutions
  • Context
  • Sample Code
  • Detection
  • Tags
  • Conclusion
  • Relations
  • More Info
  • Disclaimer
  • Credits

TL;DR: If your language has the right tool, your classes should be either abstract or final.

Problems

  • Subclassification for Code Reuse

  • Classes with just one concrete subclass

  • Liskov Substitution Violation

  • Yo-Yo Problem

Solutions

  1. Declare all your leaf classes as final and the rest of them abstract.

Context

Managing hierarchies and composition is the main task of a good software designer.

Keeping hierarchies healthy is crucial to favor cohesion and avoid coupling.

Sample Code

Wrong

public class Vehicle
{
  // class is not a leaf. Therefore it should be abstract 

  //an abstract method that only declares, but does not define the start 
  //functionality because each vehicle uses a different starting mechanism
  abstract void start();
}

public class Car extends Vehicle
{
  // class is leaf. Therefore it should be final
}

public class Motorcycle extends Vehicle
{
  // class is leaf. Therefore it should be final
}

Right

abstract public class Vehicle
{
  // class is not a leaf. Therefore it is abstract

  //an abstract method that only declares, but does not define the start 
  //functionality because each vehicle uses a different starting mechanism
  abstract void start();
}

final public class Car extends Vehicle
{
  // class is leaf. Therefore it is final
}

final public class Motorcycle extends Vehicle
{
  // class is leaf. Therefore it is final
}

Detection

[X] Automatic

Since this is enforced by static analysis, we can't do it with most available tools.

Tags

  • Subclassification

Conclusion

We should look back at our classes and start qualifying them either as abstract or final.

There are no valid cases for two concrete classes, one subclassifying the other.

Relations

More Info

Deep Subclasses

Disclaimer

Code Smells are just my opinion.

Credits

Photo by William Bossen on Unsplash


When the final design seems too simple for the amount of work you've put in, then you know you're done.

Brady Clark


This article is part of the CodeSmell Series.

 
Share this

Impressum

Technical Opinions are my own. I don't have the revealed truth.

Software Design is a creative activity. These are hints and not rigid rules.

I write on BackEnd Business Systems and OOP Design. My advice/experience might not suit other systems.

You can write me at info(at)maximilianocontieri.com