views:

83

answers:

2

Consider a web form with a dropdown. Based on the selection in the dropdown, some options are displayed - not many, say two or three for each selection. When the user clicks OK, the server creates a new object, type determined by the dropdown, attributes from the appropriate options.

So the server has to do three things based on the dropdown selection: display some data; retrieve some data, and create an object of the appropriate type. Would you use three case statements here, or build an AObjectCreator class that can be appropriately subclassed for each selection in the dropdown?

+1  A: 

Subclass.

Switch statements can get messy, fast.

geowa4
How fast? Would you go to the trouble if there were 5 options in the dropdown? How about 3? 2?
Ben Fulton
There's no formula. If there's a potential to add more options, go with objects. If cases can be complex, go with objects. Ultimately the design is up to you. Do what fit's your problem best. Subclassing is only my suggestion.
geowa4
A: 

Sounds like you need a Factory.
Take a look at the now almost synonymous PizzaFactory example

Gishu
Would you really create a factory, a base class, and two subtypes if your dropdown only had two options?
Ben Fulton
No. In that case, I'd just use an if-else and be done with it.
Gishu