org.sonar.l10n.java.rules.java.S6539.html Maven / Gradle / Ivy
"Monster Class" is a class that implements too many functionalities that are not well organized, or cohesive. Monster Classes are not created
intentionally, but rather they often arise over time as a result of poor software design or a lack of attention to good programming practices such as
modularization and encapsulation. As a software evolves and new requirements are added, it can be tempting to add new functionality to existing
classes rather than creating new classes to handle the new functionality. This leads to classes becoming bloated and difficult to understand and
maintain, ultimately resulting in a Monster Class.
Here are the characteristics of a Monster Class:
- High number of instance variables and methods
- Variables and methods that are not related to each other (low cohesion and high coupling)
- Too many responsibilities, violating the Single Responsibility Principle (aka SRP)
- Difficult to test, leading to poor test coverage and a higher risk of defects
Why is this an issue?
Monster Classes become monolithic entities, with numerous responsibilities and functionalities packed into a single class. This is problematic
because it violates the Single Responsibility Principle, which states that a class should have only one reason to change.
When a class has too many responsibilities and functionalities, it becomes difficult to maintain. Changes to one part of the class can
unintentionally affect other parts, leading to bugs. Additionally, it can be difficult to test the class, as there may be many different interactions
between different parts of the class that need to be considered.
How to fix it
There is no magical recipe. Monster Classes should be refactored and broken into smaller, more focused classes, each one with a single
responsibility. When a class has only one responsibility, it is easier to reason about its behavior and to make changes to it without affecting other
parts of the code.
Code examples
Noncompliant code example
With a threshold of 5:
class Foo { // class Foo depends on too many classes: T1, T2, T3, T4, T5, T6 and T7
T1 t1;
T2 t2;
T3 t3;
public T4 compute(T5 a, T6 b) {
T7 result = a.getResult(b);
return (T4) result;
}
}
Compliant solution
public class Bar {
T8 a8;
T9 a9;
}
Resources
Articles & blog posts