Hi all,
It has been brought up before (at least here and here if not in other places) that when using "To More Specific Class" to cast a child to a parent class, the parent's class data is not copied to the child class. I have a use case where I won't know which child to use until a while into the code, but I still want to access parent data and run parent methods before that cast to a specific child.
The only suggested solutions in the above forums were to copy the original parent instance's data to the new child instance. This works, but it's kind of cumbersome given that the only way I know to do this is with bundle/unbundle functions or property nodes or accessor functions, all of which won't accommodate automatically including new class data items and will break if you remove class data items. (The former is a much bigger problem than the latter since it will silently fail to include the added class data.) Basically, I want a stable cast function that can copy the existing parent's data to the new child.
I looked into it a bit more and wrote a quick, hacky workaround involving the flatten/unflatten XML functions, where I get the new child object's XML representation and the parent's XML representation. I take the portion of the parent's XML that represents the class data I want to maintain and simply copy that into the right part of the child's XML class data. I then unflatten the hacked together XML back to the child object type, and it actually works. I can read the original parent's data and can call my abstract parent methods and see that the correct child is dynamically dispatched and returns the child's class data. Of course, this just proves that what I want can be done. It is not a tested or production-worthy solution. It also doesn't answer the question of should it be done.
I hope (but can't seem to prove) that there is a more elegant way to programmatically get all of the values of a parent class's data and write them to a child class. I tried playing with the Data Type Parsing palette, looked in Hidden Gems and Open G, and otherwise poked and prodded to see if there was a better way to do this and didn't get far. (In fairness, those palettes would likely all just be doing XML manipulation, too, but at least I could blame bugs on others!)
Could I architect my code to not write to class data until I've determined which child to call? I mean, yeah, but is there actually a good, compelling comp sci reason why I shouldn't be able to choose which child I want to use after having called parent methods and written to class data? Is there a nicer way to copy all of my parent data to the child at once without me having to update the method if class data contents change? One side of me thinks: "If it's this awkward, you probably should do this," and the other thinks, "But why not? Are you missing something really simple?" Hoping to get your thoughts.
Thanks!
David