The Class Explosion Problem
This design uses Static Inheritance (the class tree is fixed when the code is written) for every variation. That works badly when features such as pizza toppings can be mixed in many ways.
1. Key Issues in this Design
Class Explosion (Combinatorial Nightmare)
- The Issue: To cover every mix of toppings, you need a new class for each one (e.g.,
CheeseOlivePizza,CheeseStuffedPizza,CheeseOliveStuffedPizza). - The Impact: With $N$ toppings, you may need $2^N$ classes. One more topping (like "Mushroom") means several new combination classes.
Violation of the Single Responsibility Principle (SRP)
- The Issue: A subclass like
CheeseOliveStuffedPizzacarries the logic of several separate features. - The Impact: The "Cheese" logic is spread over every subclass that includes it, so the code is hard to maintain.
Static Nature of Inheritance
- The Issue: Inheritance is fixed at compile time, before the program runs.
- The Impact: You cannot take an existing
PlainPizzaand "add" cheese at runtime when the user asks. You must throw it away and create a newCheesePizza.
Rigid and Brittle Hierarchy
- The Issue: A deep inheritance tree breaks easily.
- The Impact: If the price or logic of
PlainPizzachanges, the change reaches dozens of subclasses. This risks regression bugs (old features that break).
2. Structural Analysis
| Component | Status | Observation |
|---|---|---|
Base Class (PlainPizza) | Overloaded | Root of a tree that is too big to manage. |
| Subclasses | Redundant | Most subclasses exist only to stand for one mix of features. |
| Extension | Hardcoded | Each new feature needs several combination classes written by hand. |
3. Summary of the "Smell"
When you see a deep inheritance hierarchy where subclasses are named after combinations of features (e.g., FeatureAWithFeatureB), it is a clear sign of Class Explosion. The Decorator Pattern fixes this by using Composition (an object holding another object) instead of inheritance. You "wrap" behaviors at runtime.