views:

84

answers:

4

Lets say I have an entity Foo, and it contains a list of another entity Bar. Should Bar have a direct reference to Foo? i.e...

public class Foo
{
   public int Id {get; set;}
   public IList<Bar> Bars {get; set;}
}

public class Bar
{
   public int Id {get; set;}
   public Foo parentFoo {get; set;  //this will be set to an the Foo entity on creation
}

or do I just leave out the reference to Foo in my Bar class?

I am leaning toward leaving that reference out, but was wondering what the correct approach is here?

+3  A: 

The correct approach is to ask the question "Does Bar need to reference Foo for some reason?" Don't just place the reference there if Bar has no need to do anything with it.

AnthonyWJones
+2  A: 

It really depends on the example. If there is a need to know the parent (for example, to perform bidirectional navigation - like XmlNode etc) then you'll need it. This only really works for a single parent.

If you just need change-notifications, then events might be more versatile - in particular, events allow for multiple "parents" without prejudice.

If the child doesn't need to care about the parent, then don't bother.

Marc Gravell
+1, Beat me to it!
LukeH
+1  A: 

Leave it out unless the Bar object absolutely needs to know which Foo it belongs to.

And if you decide that it is necessary, consider how you would deal with a Bar object that belongs to more than one Foo (perfectly possible with the class structure you've described).

LukeH
+1  A: 

I'll second the answers that state "do it if you need it" but want to warn that coupling in both directions tends to lead to brittle code. Consider carefully whether or not the reference from Bar back to Foo is absolutely necessary. If it can at all be avoided, it should.

Michael Meadows