Overview
To understand a typical design anti-pattern causing Class Explosion, consider a use-case of a Restaurant. They need to serve several menu items, some of them are listed below in the form of class names.
The Problem
When designing a restaurant ordering system, we need to consider:
- Menu Items: Various food items available for ordering (Pizza, Sandwich, Burger, etc.)
- Cost Attribute: Each item needs a "cost" attribute for the ordering system
- Descriptions: Each item should have a description
- Variations: Customers have different preferences. For example, thin crust pizzas as well as thick crust pizzas
Class Explosion Example
When we try to create classes for every variation, we end up with an exponential number of classes:
- ThinCrustPizza
- ThickCrustPizza
- ThinCrustPizzaWithCheese
- ThickCrustPizzaWithCheese
- ThinCrustPizzaWithPepperoni
- ThickCrustPizzaWithPepperoni
- ThinCrustPizzaWithCheesePepperoni
- ThickCrustPizzaWithCheesePepperoni
- ... and many more combinations
The Issue
This approach creates what's known as "Class Explosion" – an unmanageable number of classes that grow exponentially with each new combination of features or toppings.
Each new requirement (a new topping, a new crust type, a new size) requires creating new classes for every possible combination, leading to:
- Code duplication
- Maintenance nightmare
- Violation of the DRY (Don't Repeat Yourself) principle
- Difficult to add new features
- Poor scalability
Solution
The Decorator pattern, explained in subsequent posts, provides an elegant solution to this problem by allowing you to add behavior (like toppings) to objects dynamically at runtime, rather than creating a new class for every possible combination.