Skip to main content
Home / Blog / Design Anti Pattern – Class Explosion

Design Anti Pattern – Class Explosion

Brevitaz Team April 24, 2019 1 min

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:

  1. Menu Items: Various food items available for ordering (Pizza, Sandwich, Burger, etc.)
  2. Cost Attribute: Each item needs a "cost" attribute for the ordering system
  3. Descriptions: Each item should have a description
  4. 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.

BT

Brevitaz Team

A member of the Brevitaz team sharing insights on software engineering, big data, and cloud technologies.

Back to all articles