C# Programming Practices – Is Child to Parent Linking a Bad Idea?

cprogramming practices

I have a situation where my parent knows about it's child (duh) but I want the child to be able to reference the parent. The reason for this is that I want the child to have the ability to designate itself as most important or least important when it feels like it. When the child does this, it moves it to the top or bottom of the parent's children.

In the past I've used a WeakReference property on the child to refer back tot he parent, but I feel that adds an annoying overhead, but maybe it's just the best way to do it.

Is this just a bad idea? How would you implement this ability differently?

Update 1:
Adding more context. This is a rendering system so the parent container is a list of windows grouped together. The child item (window) that says "I'm most important!" wants to basically be rendered on the top of the rest of the windows.

The parent is just a logical container to group these children together. I can see where adding an event to signal the request to be on the top is a good idea. But implementation (what the child wants to do with the parent) aside, why wouldn't you want to have child->parent linking? Doubly linked lists do this so people can traverse to and from something.

Best Answer

Is this just a bad idea?

Oftentimes.

  • It breaks encapsulation of the parent.
  • It increases coupling in both.
  • It serves as a breakout point for the child to get at the rest of the system, increasing coupling with anything vaguely near it (because people will abuse that reference)
  • It limits your design if you ever want children without parents.

How do do it better? The child should not know or care that it is in a collection. Instead of deeming itself important, it should signal that some event it knows about has happened so whomever cares (the parent) can increase its priority (or whatever is the rules for the context the child lives in). I'm not thrilled by that, and would perhaps prefer a better separation of concerns between the child's model and the importance behavior, but can't elaborate without more context.

[edit:]

Yeah, rendering systems are one case where parent ownership... well I don't want to say makes sense, but it's one case where it has been done and isn't the end of the world. For giving a control focus, I would still prefer the design where the input handler (or whatever) walks the tree and knows which collection to reorder rather than it finding the child, calling something on it which knows to go to its parent.

Related Topic