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?
-
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.
-
It really depends on the example. If there is a need to know the parent (for example, to perform bidirectional navigation - like
XmlNodeetc) 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.
LukeH : +1, Beat me to it! -
Leave it out unless the
Barobject absolutely needs to know whichFooit belongs to.And if you decide that it is necessary, consider how you would deal with a
Barobject that belongs to more than oneFoo(perfectly possible with the class structure you've described). -
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
Barback toFoois absolutely necessary. If it can at all be avoided, it should.
0 comments:
Post a Comment