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
- 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;
}
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;
}
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
More Info
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
This article is part of the CodeSmell Series.
About the author
I’m a senior software engineer loving clean code, and declarative designs. S.O.L.I.D. and agile methodologies fan.
Comments
Join the discussionInteresting point of view. How do you feel about a class of classes, e.g.
public static class GlobalConstants
{
public static class MaxPlayers
{
public const int MaxPlayers = 10;
}
public static class DefaultLanguage
{
public const string DefaultLanguage = "en-US";
}
public static class Math
{
public const double Pi = 3.14159;
}
}
IMHO, Nested classes are yet another code smell
Code Smells
In this series, we will see several symptoms and situations that make us doubt the quality of our developments. We will present possible solutions. Most are just clues. They are no hard rules.





