Programming Challenge: Deep Copy, Overriding Some...

  • Imagine that you have a hierarchical object graph:

hierarchy

And you want to merge two instances. Some elements should combine elements from both, some must take their value from the master. My example scenario is artificial, so please don't say 'well, if all you have to do is number pages...'

This is my first take:

You can see my pattern:

  • shallow copy
  • combine
  • override
  • recurse

I have two problems with this code:

  1. It's tedious
  2. The biz rules are spread out to individual classes, but they are more naturally expressed in a single place, e.g., "Merge these two, but use this one as the 'master' and use it's values for Foo.Bar, Bar.Bat, and Baz.Fizz"

(Something I'm not bothered about is the explicit call to GetSomeMergeableElement().DeepCopyDeferringToMaster() -- I could use reflection to iterate over the IMergeable fields and call
someGetterFunction(newFoo). DeepCopyDeferringToMaster( someGetterFunction(other), someGetterFunction(master) );
but I would have to cut-and-paste that loop into each subclass, so no real gain.)

[I have a strong hunch that this could be done better in a functional language, but I can't put it together. Can you?]{style="text-decoration: line-through;"}

Update: Here's my FP-inspired implementation -- what do you think?

Here's the test code: