I'm trying to figure out the best way to create a structure of classes
that will remain "valid" to a set of rules as instances are created,
changed, and removed.
I have three classes that have a hierarchical relationship to one another.
Building-References one or more Mass instances
-Can not exist with out at least one child Mass instance
-Deleting or removing the last associated Mass insatnce should also remove the Building instance
Mass
-Can be related to only one Building instance
- Can be "orphaned" and not related to any Building instance
Level-Must be related to at least one Mass instance
-Can be related to multiple Mass instanced as long as they share the same Building class parent
For
example say I want to associate a Level with a Mass. I need to check if
the mass is associated with a building, and if the level is associated
with another Mass, and if that mass is also associated with a building.
If I associate a level that is already part of a building to a mass
that is not part of a building that mass needs to be added to the
building. Or if they are both already part of different buildings I
want to throw and error. Etc.. etc..
Here's a diagram:
http://dl.getdropbox.com/u/113068/Visio-Building%20Structure%20Diagram.pdfSo now I have a
ProjectClass
in which contain a list of all the current
Building and Mass instances. Any manipulation like adding a Building
or associating/dissociating a Mass to/from a building is done through
methods attached to the ProjectClass. Each of those methods contains a
bunch of nested if statements and foreach loops to figure out what
should be done when objects are added, removed, or associated with one
another.
This
method, however, is getting really really messy so I'm wondering if
there is a better way? Although it's not obvious to me how you could
get behavior like this simply through the class structure. I'm thinking it would be better to have one "Validate" or "Purge" method attached to the ProjectClass that is run after any change that will automatically purge Buildings with out related Masses, or make other changes to make sure everything fits within the "rules".
Eric