Skip to content

Latest commit

 

History

History
124 lines (73 loc) · 4.68 KB

File metadata and controls

124 lines (73 loc) · 4.68 KB

Code Smell 114 - Empty Class

Code Smell 114 - Empty Class

Have you encountered classes without behavior? Classes are their behavior.

TL;DR: Remove all empty classes.

Problems

Solutions

  1. Remove the classes and replace them with objects instead.

  2. If your classes are Anemic Exceptions, remove them.

Context

Many developers still think classes are data repositories.

They couple different behavior concept with returning different data.

Sample Code

Wrong

class ShopItem { 
  code() { }
  description() { }                 
}

class BookItem extends ShopItem { 
   code() { return 'book' }
   description() { return 'some book'}     
}

// concrete Class has no real behavior, just return different 'data'

Right

class ShopItem { 
  constructor(code, description) {
    // validate code and description
    this._code = code;
    this._description = description;
  }
  code() { return this._code }
  description() { return this._description }                 
  // Add more functions to avoid anemic classes
  // getters are also code smells, so you need to iterate it
}

bookItem = new ShopItem('book', 'some book);
// create more items

Detection

[X] Automatic

Several linters warn us of empty classes.

We can also make our own scripts using metaprogramming.

Tags

  • Behavior

Conclusion

Classes are what they do, their behavior.

Empty classes do nothing.

Relations

Code Smell 26 - Exceptions Polluting

Code Smell 40 - DTOs

Code Smell 60 - Global Classes

Code Smell 01 - Anemic Models

Code Smell 136 - Classes With just One Subclass

More Info

Credits

Photo by Kelly Sikkema on Unsplash


An error arises from treating object variables (instance variables) as if they were data attributes and then creating your hierarchy based on shared attributes. Always create hierarchies based on shared behaviors, side.

David West

Software Engineering Great Quotes


This article is part of the CodeSmell Series.

How to Find the Stinky Parts of your Code