DEV Community

Cover image for Code Smell 202 - God Constant Class
Maxi Contieri
Maxi Contieri

Posted on • Originally published at maximilianocontieri.com

2

Code Smell 202 - God Constant Class

Constants should be together to find them easily

TL;DR: Don't define too many unrelated constants in the same class. Don't pile up the junk together.

Problems

  • Bad Cohesion

  • High Coupling

  • Magic Numbers

  • Single Responsibility principle violation

Solutions

  1. Break the contents following Real World responsibilities using the MAPPER.

Context

This is a special case of a God Object restricted only to constant definitions.

The repository can be a class, file, or JSON.

Sample Code

Wrong


public static class GlobalConstants
{
    public const int MaxPlayers = 10;
    public const string DefaultLanguage = "en-US";
    public const double Pi = 3.14159; 
}


Enter fullscreen mode Exit fullscreen mode

Right


public static class MaxPlayersConstants
{
    public const int MaxPlayers = 10;    
}

public static class DefaultLanguageConstants
{
    public const string DefaultLanguage = "en-US";
}

public static class MathConstants
{
    public const double Pi = 3.14159;
}


Enter fullscreen mode Exit fullscreen mode

Detection

[X] Semi-Automatic

We can tell our linters to warn us of too many constants' definitions against a preset threshold.

Tags

  • Coupling

Conclusion

Finding correct responsibilities is one of our primary tasks when designing software.

Relations

https://maximilianocontieri.com/code-smell-14-god-objects

https://maximilianocontieri.com/code-smell-29-settingsconfigs

https://maximilianocontieri.com/code-smell-02-constants-and-magic-numbers

More Info

Medium

Disclaimer

Code Smells are my opinion.

Credits

Photo by Aaron Burden on Unsplash


If someone says their code was broken for a couple of days while they are refactoring, you can be pretty sure they were not refactoring.

Martin Fowler

https://maximilianocontieri.com/software-engineering-great-quotes


This article is part of the CodeSmell Series.

https://maximilianocontieri.com/how-to-find-the-stinky-parts-of-your-code

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

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