2

In a legacy codebase I have a very large class with far too many fields/responsibilities. Imagine this is a Pizza object.

It has highly granular fields like:

  • hasPepperoni
  • hasSausage
  • hasBellPeppers

I know that when these three fields are true, we have a Supreme pizza. However, this class is not open for extension or change, so I can't add a PizzaType, or isSupreme(), etc. Folks throughout the codebase duplicate the same if(a && b && c) then isSupreme) logic all over place. This issue comes up for quite a few concepts, so I'm looking for a way to deconstruct this object into many subobjects, e.g. a pseudo-backwards Builder Pattern.

PizzaType pizzaType = PizzaUnbuilder.buildPizzaType(Pizza); //PizzaType.SUPREME

Dough dough = PizzaUnbuilder.buildDough(Pizza);

Is this the right approach? Does this pattern exist already?

Cœur
  • 37,241
  • 25
  • 195
  • 267

2 Answers2

4

How about the Adapter Pattern?

Basically a wrapper class that has all the functionality you really want which can go easily back and forth to a Pizza class.

MenuPizza myPizza = new MenuPizza(pizza);
PizzaType pizzaType = myPizza.getPizzaType();
DoughType doughType = myPizza.getDoughType();

And you could provide the reverse functionality...

MenuPizza otherPizza = new MenuPizza(PizzaType.SUPREME, DoughType.SOUR);
Pizza pizzaPOJO = otherPizza.getPizzaPOJO();
Tim Bender
  • 20,112
  • 2
  • 49
  • 58
  • I also have similar question related to Single Responsibility Principle Model [here](http://stackoverflow.com/questions/29742523/how-to-follow-single-responsibility-principle-in-my-httpclient-executor). If possible, can you help me out over there. Any help will be greatly appreciated. – john Apr 20 '15 at 21:56
0

I think this would be a great use case for extension functions, which don't exist in java. In lieu of that the simplest solution in my mind is to create a class and add the methods that would be extensions into that utility class as static methods; PizzaUtils.isSupreme(Pizza pizza).

Charles Durham
  • 2,445
  • 16
  • 17