Sometimes we run into a problem where a class doesn't need to use its own properties. See approach A:
struct Ball {
double mass = 1;
double x = 0;
double y = 0;
};
struct World {
std::vector<Ball*> balls;
void run_physics() {
// here we run the physics
// we can access every ball and their x, y properties
}
};
In order to avoid this, we can use approach B:
struct World;
struct Ball {
World* world = NULL;
double mass = 1;
double x = 0;
double y = 0;
void run_physics() {
if (this->world != NULL) {
// here we run the physics again
// we can access every other ball properties through this->world->balls vector.
}
}
};
struct World {
std::vector<Ball*> balls;
};
But approach B is a tight-coupling structure, which means that both Ball and World know about each other, which is not good.
So, which is better approach?
- A: Loose-coupling, but some classes will not use their own properties, or
- B: Classes will use their properties, but tight-coupling structure ?
When to use each one?
A is better in that is more extensible.
Balls might take on other properties not relevant to the current calculation, such as members for calculating the moment of inertia (if a hollow sphere for example).
So yes, it is acceptable for a class to have its properties used only by the outside environment, since that might not be the case for ever.
That said, if
xandytell you something about the locations of the ball, then those are more to do with a class telling you about the collection of installed ball instances, rather than being part of the ball itself.