Reputation: 11852
Here's an example case:
public list getPizzaIngredients(pizzaName) { if pizzaName = HAWAIIAN return [ CHEESE, TOMATO SAUCE, PINEAPPLE, HAM]; if pizzaName = ITALIAN return [ CHEESE, TOMATO SAUCE, PEPPERONI, OLIVES]; if pizzaName = MEATLOVERS return [ CHEESE, TOMATO SAUCE, PEPPERONI, BACON, SAUSAGE, OLIVES]; return null; }
Here we are repeating ingredients in each list. An alternative way to do is:
public list getPizzaIngrediants(pizzaName) { ing = []; ing.add(CHEESE) ing.add(TOMATO SAUCE); if pizzaName in (HAWAIIAN) ing.add(PINEAPPLE); if pizzaName in (HAWAIIAN) ing.add(HAM); if pizzaName in (ITALIAN, MEATLOVERS) ing.add(PEPPERONI); if pizzaName in (ITALIAN, MEATLOVERS) ing.add(OLIVES); if pizzaName in (MEATLOVERS) ing.add(BACON); if pizzaName in (MEATLOVERS) ing.add(SAUSAGE); return ing;
or we could make it more concise:
public list getPizzaIngrediants(pizzaName) { ing = []; ing.add(CHEESE,TOMATO SAUCE) if pizzaName in (HAWAIIAN) ing.add(PINEAPPLE, HAM); if pizzaName in (ITALIAN, MEATLOVERS) ing.add(PEPPERONI, OLIVES); if pizzaName in (MEATLOVERS) ing.add(BACON, SAUSAGE); return ing;
Now personally - although the first example is wordier and involves repeating the variables, it's far more readable and easier to modify than the other two solutions.
Is there a convention around this kind of programming style/issue?
Upvotes: 1
Views: 50
Reputation: 1865
If you just have constants HAWAIIAN ITALIAN MEATLOVERS, put them in an enum, preferably in the first format - nice and readable.
If pizza and toppings are, as is very likely, going to be real concepts with the potential for future change (VEGGIE?!? kinds of cheese?), all of these will break, in the sense that there is no one change to make to your code. All it takes is a second property of pizza besides ingredients (price()? tasty()?) and for each new pizza you must write code in multiple places. Then you should use a proper object oriented design, a class hierarchy with subclasses of abstracts Pizza and Ingredients.
There is a lengthy pizza store example covering very similar ground in the Factory chapter of Head First Design Patterns.
Upvotes: 2