DEV Community

Cover image for Code Smell 14 - God Objects
Maxi Contieri
Maxi Contieri

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

1

Code Smell 14 - God Objects

An object that knows too much or does too much.

TL;DR: Don't take too many responsibilities.

Problems

  • Cohesion

  • Coupling

Solutions

  • Split responsibilities.
  • Follow Single Responsibility Principle.
  • Follow The Boy Scout Rule.

Examples

  • Libraries

Exceptions

Sample Code

Wrong

class Soldier {
   run(){}
   fight(){}
   driveGeneral(){}
   clean() {} 
   fire() {} 
   bePromoted() {}
   serialize() {}
   display() {} 
   persistOnDatabase() {}
   toXML() {}
   jsonDecode(){}

  //...     
  }
Enter fullscreen mode Exit fullscreen mode

Right

class Soldier {
   run() {}
   fight() {}
   clean() {}    
  }

Enter fullscreen mode Exit fullscreen mode

Detection

Linters can count methods and warn against a threshold.

Tags

  • Cohesive

Conclusion

Libraries were fine in the 60. In Object-Oriented Programming, we will distribute responsibilities among many objects.

Also Known as

  • Large Class

Relations

More info

Credits

Photo by Francisco Ghisletti on Unsplash


This article is part of the CodeSmell Series.

Last update: 2021/06/21

Dev Diairies image

User Feedback & The Pivot That Saved The Project

🔥 Check out Episode 3 of Dev Diairies, following a successful Hackathon project turned startup.

Watch full video 🎥

Top comments (2)

Collapse
 
pyrsmk profile image
Aurélien Delogu

For those who might pass by, this problem can be solved with the composition pattern.

Collapse
 
mcsee profile image
Maxi Contieri

indeed. but it might be overdesign sometimes

AWS Q Developer image

Build your favorite retro game with Amazon Q Developer CLI in the Challenge & win a T-shirt!

Feeling nostalgic? Build Games Challenge is your chance to recreate your favorite retro arcade style game using Amazon Q Developer’s agentic coding experience in the command line interface, Q Developer CLI.

Participate Now

👋 Kindness is contagious

If this **helped, please leave a ❤️ or a friendly comment!

Okay