Suppose I have a POCO class containing foos and bars :
public class Poco { public IEnumerable<Foo> Foos { get { return foos; } } public IEnumerable<Bar> Bars { get { return bars; } } private List<Foo> foos; private List<Bar> bars; }
In my example, I need to be able to add and remove foos and bars :
public class Poco { public IList<Foo> Foos { get { return foos; } } public IList<Bar> Bars { get { return bars; } } private List<Foo> foos; private List<Bar> bars; }
But let's say that I also need a (arbitrary) restriction that there must be one foo per bar , and also one bar per foo .
public class NotAPocoAnyMore { public IEnumerable<Foo> Foos { get { return foos; } } public IEnumerable<Bar> Bars { get { return bars; } } private List<Foo> foos; private List<Bar> bars; public void Add(Foo f, Bar b) {...} public void Remove(Foo f, Bar b) {...} }
My question is this: am I getting ready to try to keep POCO simple and not give it any useful methods? The first example of POCO is good because it is immutable, and POCOs have other advantages. However, I see no way to preserve the POCO class and still have ways to access and modify the contents in a controlled way (at least not as if it werenโt too hard to kill).
Some thought I had:
Nested Modifier Class
public class Poco { public IEnumerable<Foo> Foos { get { return foos; } } public IEnumerable<Bar> Bars { get { return bars; } } public PocoModifier Modifier { get { ... } } private List<Foo> foos; private List<Bar> bars; public class PocoModifier { private readonly Poco toModify; public void Add(Foo f, Bar b) {...} public void Remove(Foo f, Bar b) {...} ... } }
Open nested class? No thanks! In addition, it is really the same as the non-POCO class, with a little nesting.
Using Access Modifiers
public class Poco { public IEnumerable<Foo> Foos { get { return foos; } } public IEnumerable<Bar> Bars { get { return bars; } } public PocoModifier Modifier { get { ... } } internal List<Foo> foos; internal List<Bar> bars; } public class PocoModifier { private readonly Poco toModify; public void Add(Foo f, Bar b) {...} public void Remove(Foo f, Bar b) {...} ... }
Slightly better, but each POCO requires a whole deployment unit.