Here's a part of a class "hierarchy" that I use for a simulation model (my code is in Python, but I think my question isn't language dependent):
class World:
# highest-level class, which "knows" everything about the model
# most likely will have just one instance
# contains (e.g., in a dictionary) references to all the instances of class Agent
class Agent:
# each instance represents an agent
# an agent can, among other things, move around according to certain rules
# movement depends on the internal state of the agent,
# but also on the terrain and other information not stored in the Agent instance
Question: where should I put the move
instance method?
I thought I'm supposed to limit the dependency of class Agent
to classes lower in the hierarchy than itself (i.e., classes whose instances are contained in Agent
instances). But that means move
method cannot be in class Agent
since it creates a dependency on (at least the interface of) classes that describe terrain, etc - so I might as well add to Agent
a reference to (and hence a dependency on) World
. Is this ok from software design perspective?
The alternative is to put method move
in class World
, where it won't cause any additional dependencies. However, class World
would then be doing almost all the work, and it seems to me that it would go against the main idea of OOP (which I understand as not to pile all the functionality into one place, but rather contain it in the relevant classes).
Performance considerations are only of minor concern (and I don't think performance would differ between the two approaches anyway).
EDIT: I misused the words "class hierarchy" above. I wasn't referring to inheritance hierarchy, just to a bunch of classes whose instances contain each other.