I’d like some guidance on which class should hold certain information. If I have a ‘Mobile Object’ that moves around within a ‘Space Object,’ does the Mobile Object really care where it is within the Space Object, how fast it’s moving, and in which direction?
It certainly seems convenient to assign a property to the Mobile Object for ‘Location,’ but I don’t think it really has any concern for that. So I’ve come up with:
class Mobile
{
//some properties/fields/etc
event EventHandler<MovementEventArgs> move;
public void Move(Vector direction)
{
raiseMove(direction);
}
private raiseMove(Vector direction)
{
EventHandler<MovementEventArgs> handler = move;
if (move != null)
handler(this, New MovementEventArgs(direction));
}
}
class Space
{
Mobile someObject;
Vector someObjectLocation;
public Space()
{
someObject = new someObject();
someObject.Move += HandleMobileMove;
}
public void MoveSomeObject(Vector direction)
{
someObject.Move(new Vector(1,0));
}
private void HandleMobileMove(object sender, MovementEventArgs e)
{
someObjectLocation += e.Direction;
}
}
That’s a bit hastily written… but I hope it gets my point across. In summary: should the Mobile hold a location, or the Space? Who should control the movement?
In WPF, the Canvas object is responsible for knowing the location of its children. That would lend credence to your approach (which uses a similar structure as an Attached Property).
If you are uncomfortable with the location being stored in the Space object, you could also use the Decorator pattern to attach additional information to the Mobile objects. This would give you the option of positioning an object or not, without the object itself caring.
When getting the collection of children, you could filter out only those objects which employ your location decorator (perhaps using the OfType extension method) and do what you need with them. You’ll have to convert to using interfaces rather than hard class references. That would probably be a good thing, though.
In the end, though, it depends on what your Space and Mobile objects are doing. If the Space object is displaying the Mobile objects (like Canvas), then it needs to know location information but the Mobiles don’t. On the other hand, if the Mobiles themselves are using their location information to track something or perform some task (and the Space object doesn’t care, perhaps only providing bounds, etc.), then it may be best to store that information with them.
To drive the point home a bit further, ask yourself this question: if I change the location, who cares? A Control is WPF is generally not affected by its Top and Left coordinates but its container control is, so it makes sense to store that information in the container. If you change the location of a Mobile, does that have any effect on the Mobile or how it does its job? Does Space behave differently if Mobile X moves from Y to Z?