views:

35

answers:

2

Lets assume I have a simple class called Category, with properties Id, Name. I want to show these as a menu in the UI. But the display logic is also affected by a third property, IsSelected, that I have to take account when I'm rendering the menu.

There are plenty of different ways to achieve this, for instance by inheriting or using partial classes. But is it really necessary that my code would change from something like

List<Category> list = CategoryLogic.GetCategories();

to

List<UICategoryItem> list = UICategoryLogic.GetCategories(intSelected);

This seems kinda overkill for such a small thing, but it's the only way I can think of. I can reduce the amount of new code required by using inheritance, but I'm still looking at least 2 new code files ( UICategoryLogic and UICategoryItem ) that might require changing if the Category changes.

Not to mention the situation where my UI uses category differently in different places, which each might have some unique properties. I could quickly end up with bunch loads of different kind of Category classes for each purpose, and it could make the code hard to follow. Also I might use something like datasets which can't be easily inherited, or maybe I'm using ORM that makes classes difficult to inherit and extend.

Is there a general pattern for situations like this, where I need to extend the basic dataitem to suite my needs?

+1  A: 

Dump out the inheritance kool-aid, composition is your friend. Keep your Category class and encapsulate it in something more suitable for your purpose.

jonathan.cone
+1  A: 

The "general pattern" for UI development is MVC - Model View Controller. Let your Category object be a part of the model and your UI controls (Lists combo boxes etc.) be the views, these have concepts like selection state, controllers are what perform the logic mapping inputs on the UI controls to changes to your model objects and where necessary updating the view objects to reflect changes.

Tom