Large Class
Large classes are difficult to understand and make it harder to change or reuse behavior. Tests for large classes are slow and churn tends to be higher, leading to more bugs and conflicts.
Symptoms
⢠You canât easily describe what the class does in one sentence. ⢠You canât tell what the class does without scrolling. ⢠The class needs to change for more than one reason. ⢠The class has more than 7 methods. ⢠The class has a total flog score of 50.
Solutions
- Move Methodâ to move methods to another class if an existing class could better handle the responsibility.
- Extract Classâ if the class has multiple responsibilities.
- Replace Conditional with Polymorphism if the class contains private methods related to conditional branches.
- Extract Value Object if the class contains private query methods.
- Extract Decorator if the class contains delegation methods.
- Replace Subclasses with Strategiesâ if the large class is a base class in an inheritance hierarchy.
Prevention
- Follow Single Responsibility Principle to prevent large classes
- Using Composition Over Inheritanceâ make it easier to create small classes.
- If a large portion of the class is devoted to instantiating subclasses, try following the Dependency Inversion Principle
- Following the Open Closed Principle will prevent Large Classes by preventing new concerns from being introduced.