I'm new to OOP and a lot of times I become stumped in situations similar to this example:
Task: Generate an XML document that contains information about a person. Assume the information is readily available in a database. Here is an example of the structure:
<Person> <Name>John Doe</Name> <Age>21</Age> <Address> <Street>100 Main St.</Street> <City>Sylvania</City> <State>OH</State> </Address> <Relatives> <Parents> <Mother> <Name>Jane Doe</Name> </Mother> <Father> <Name>John Doe Sr.</Name> </Father> </Parents> <Siblings> <Brother> <Name>Jeff Doe</Name> </Brother> <Brother> <Name>Steven Doe</Name> </Brother> </Siblings> </Relatives> </Person>
- Ok lets create a class for each tag (ie: Person, Name, Age, Address) Lets assume each class is only responsible for itself and the elements directly contained
- Each class will know (have defined by default) the classes that are directly contained within them
- Each class will have a process() function that will add itself and its children to the XML document we are creating
- When a child is drawn, as in the previous line, we will have them call process() as well
Now we are in a recursive loop where each object draws their children until all are drawn
But what if only some of the tags need to be drawn, and the rest are optional? Some are optional based on if the data exists (if we have it, we must draw it), and some are optional based on the preferences of the user generating the document
- How do we make sure each object has the data it needs to draw itself and its children? We can pass down a massive array through every object, but that seems shitty doesn't it? We could have each object query the database for it, but that's a lot of queries, and how does it know what its query is?
- What if we want to get rid of a tag later? There is no way to reference them.
I've been thinking about this for 20 hours now. I feel like I am misunderstanding a design principle or am just approaching this all wrong. How would you go about programming something like this?
I suppose this problem could apply to any scenario where there are classes that create other classes, but the classes created need information to run. How do I get the information to them in a way that doesn't seem messy?