Reputation: 5302
I have an object and class that contains it.
The first example shows that the object has a special function called Action
, and the container calls it when necessary. The point is that Action
is built in Object class.
The second example shows that the object is simpler, it doesn't have Action
, but it is implemented as function in Container class, and applied to some object.
What are the differences between these two approaches, what are the problems related to them?
public class Object
{
Vector2 position;
//ecc
//Constructor
void Action()
{
//...
}
//ecc.
}
public class Container
{
List<Object> mylist = new List<Object>();
//something
//Constructor
public void Update(GameTime gametime)
{
//something
Object obj = //Random object from list
obj.Action();
}
}
public class Object
{
Vector2 position;
//ecc
//Constructor
//Without action
//ecc.
}
public class Container
{
List<Object> mylist = new List<Object>();
//something
//Constructor
public void Action(Object obj)
{
//Do the same thing as done above to obj
}
public void Update(GameTime gametime)
{
//something
Object obj = //Random object from list
Action(obj);
}
}
Upvotes: 0
Views: 138
Reputation: 12849
The difference is that you might be lowering cohesion and violating Information Expert GRASP principle. Which says that methods should be in object, that contain most data the method uses. In your case, it is obvious the method only works on fields of an Object
. This results in lower cohesion. Also, it creates tight coupling between the collection and the object, which for example, makes it hard to subclass the Object
and make Action
do something more.
On the other side, related to XNA tag you are using, the second option might be a start for optimalization. If you make the Object
a struct
and use a ref
modifier, you might save some ticks of CPU for processing this object. This might come in handy if you have a huge array of those objects. Like hundreds of thousands. Like a particle system.
Upvotes: 1