While trying to simulate my domain, I encountered the following problem. Let us have a Thing:
class Thing
{
public int X { get; set; }
}
Things have property X. Then there are Packages that combine Things. But the domain requires a restriction on things that may contain packages. Let it be, for example, that the cumulative value of Xes cannot be above some certain limit:
class Pack
{
private readonly List<Thing> myThings = new List<Thing>();
private const int MaxValue = 5;
public void Add(Thing thing)
{
if (myThings.Sum(t => t.X) + thing.X > MaxValue)
throw new Exception("this thing doesn't fit here");
myThings.Add(thing);
}
public int Count
{
get { return myThings.Count; }
}
public Thing this[int index]
{
get { return myThings[index]; }
}
}
So, I check before adding Thing to Pack for the condition, but it's still so easy to get into trouble:
var pack = new Pack();
pack.Add(new Thing { X = 2 });
pack.Add(new Thing { X = 1 });
var thingOne = new Thing { X = 1 };
var thingTwo = new Thing { X = 3 };
pack.Add(thingOne);
thingOne.X = 5;
pack[0].X = 10;
In C ++, the solution would be to create a copy when you insert and return a const link in the index. How to design around this problem in C # (and possibly Java)? I just can't think of a good solution:
- make Thing immutable - but what if it has to be volatile?
- /, , Thing; , ? - Pack - .
?
EDIT:
... . .
, , Thing , , . ... . " ", "" ( DDD) , , , , ( ).
, ++ const. , , .