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?