I'm laying out the foundations for a potential game, but I'm having trouble designing the classes to be encapsulated yet efficient.
Generally, people say objects should rely little on each other to preserve modularity and encapsulation.
However, sometimes it seems convenient to have some object know about each other.
Let's say we have a class called Dog.
public class Dog {
public void eat() { ... }
public void wagTail() { ... }
}
Dogs have owners, so there is a dog owner class.
public class DogOwner {
private Dog dog;
public Dog getDog() { return dog; }
public void petDog() { ... }
public void takeDogForWalk() { ... }
}
Now, what if we have a Dog
, but we don't have its owner? It seems to make sense to make a getOwner()
method for Dog
.
public class Dog {
private DogOwner owner;
public void eat() { ... }
public void wagTail() { ... }
public DogOwner getOwner() { return owner; }
}
However, this now gives Dog
information about the DogOwner
, which seems to violate information hiding. It also seems to create redundancy, because Dog
has a DogOwner
, and DogOwner
has a Dog
.
Another way to find the owner is to simply look through all the owners, and find the corresponding dog. Though this will not create dependency of Dog
and DogOwner
, this seems a lot more expensive than it needs to be, because we have to cycle through all the owners.
So, is it alright for Dog
to have a getOwner()
method? If it is not, what other alternatives are there to efficiently access the owner if only the Dog
is known?
"Should rely little" - just as much as is needed, not more, not less.
Of course the dog can have a link to its owner. You asked about the alternatives: One, to always carry the dog and the owner information together, even when lots of code doesn't care about the owner. Two, if you have a dog and don't know the owner, you obviously can't ask the owner. You could have a hash table mapping dogs to owners, but then you might as well just store the dog with the owner. Or you have a database of all dog owners and scan it for an owner of that dog - not exactly scaleable.