Design Anti Pattern – Class Explosion

To understand a typical design anti-pattern causing Class Explosion, consider a use-case of Restaurant. They need to serve several menu items, some of them are listed below in form of Class names.

  • DoubleCheesePizza
  • ItalianPizza
  • FreshVeggiePizza
  • Vegetable Sandwich
  • Cheese Sandwich
  • Aalu-matar Sandwich

We also need to take care of our ordering system in hotel so we need one attribute called “cost” in all of the above classes. We will have descriptions of each item. Keeping in mind likings of customers, we need to have thin crust pizzas, as well as thick crust pizza. So lets have a look at these classes.

public class DoubleCheesePizza {
private List ingredients;
private String description;
private String crustType; // Thin crust or thick crust
private String size; // Small, Medium or Large

public doublecost() {
// Calculate Cost For DoubleCheesePizza
}
// Other getters and setters

}

Here we have ingredients for printing purpose and we have cost() method in each class, which will calculate cost of item based on its attributes e.g. crustType, size etc. Similarly, we will have FreshVeggiePizza and ItalianPizza. But being in Gujarat, we need to remember Jains also so we will include one additional boolean attribute “withOnion”, so that we can have it true or false. We can also have provision to have grated cheese or liquid cheese. We will need a boolean for “liquidCheese”. CheeseSandwich class can be like this:

public class CheeseSandwich {
private String name;
private String description;
private List ingredients;
private boolean withExtraCheese;

public double cost() {
// Calculate Cost For DoubleCheesePizza
}
// Other getters and setters
}

Remember, we need to add many more items in our menu as Objectville gets popular. So just imagine a scenario when Objectville will be among the most popular restaurants. Customers will definitely expect flexibilities like have some extra cheese in pizza, have some customized toppings like jalapano and olives in freshVeggie. Exclude capsicum from Italian pizza, have “grilled” vegetable sandwich, have some cheese on Aaloo-matar sandwich. And cost is going to vary according to toppings used. If we go with this same design, we will end up with something like this.

Class Explosion

Class Explosion

So one problem we see clearly here is explosion of classes. We need to create a class for every customization in the item. May it be some single addition in topping or some different method in cooking. The other problem here is, our cost() method becomes tightly coupled. What will we do if price of cheese goes up. This design really seems like a design anti pattern, when we are well equipped with power of inheritance, polymorphism & aggregation. This is the kind of class design that we really don’t want. We will try to get rid of these issues next time. Next>>

Write a comment