views:

87

answers:

3

This is in my opinion an abstract problem and I hope I can explain it well. I happened to find the same kind of problem in a completely different project and now I have it again and I would like to avoid it if possible.

I'm creating some classes to simplify some tasks for some specific requirements we have in some projects at work.

I have a class that creates objects which maps the values from webcontrols to an object properties similar to this

http://msdn.microsoft.com/en-us/library/aa478957.aspx

The problem I have it's sometimes I have to store a non container object in a place (in an object's attribute) and sometimes I have to a store a container object in the same place for storing the values of a webcontrol (a webcontrol can sometimes hold several values like a checkboxlist). I dont like this at all, because some time ago when working in a non commercial compiler, when parsing and generating the intermediate code I had sometimes to store a container in a place, and sometimes I had to store a non container in the same place, and having to ask in other parts of the code if what you are reading is this type of object, or this another type of object, it is something really annoying and it mess up the code. Is there any tips about what it would be better to do to avoid this kind of situations or nothing can be done to avoid it sometimes?

+1  A: 

I'm not sure I understand your question, but maybe Visitor pattern is what you are looking for?

witzar
are you familiar with the mini-c to assembler compiler made in cPython that's around in the web? is the visitor pattern you are refering to the same used in the upper levels of that compiler?
Pablo
unfortunately i'm not familiar
witzar
+1  A: 

Sounds like composite pattern to me. Composite will provide an interface for treating containers of objects and leaf objects (those that are not containers) the same.

mjh2007
+1  A: 

This is the Polymorphism problem.

"sometimes I have to store a non container object in a ... an object's attribute and sometimes I have to a store a container object in the same place"

You have two things which should be made polymorphic.

The easiest way to fix this is to use a container always. When you want to store a single non-container object, you "wrap" it in a container that contains just the one object.

Then you always have containers. Sometimes the container has one object, sometimes it has more than one.

S.Lott