Relative encapsulation design
- by taher1992
Let's say I am doing a 2D application with the following design:
There is the Level object that manages the world, and there are world objects which are entities inside the Level object.
A world object has a location and velocity, as well as size and a texture. However, a world object only exposes get properties. The set properties are private (or protected) and are only available to inherited classes.
But of course, Level is responsible for these world objects, and must somehow be able to manipulate at least some of its private setters. But as of now, Level has no access, meaning world objects must change its private setters to public (violating encapsulation).
How to tackle this problem? Should I just make everything public?
Currently what I'm doing is having a inner class inside game object that does the set work. So when Level needs to update an objects location it goes something like this:
void ChangeObject(GameObject targetObject, int newX, int newY){
// targetObject.SetX and targetObject.SetY cannot be set directly
var setter = new GameObject.Setter(targetObject);
setter.SetX(newX);
setter.SetY(newY);
}
This code feels like overkill, but it doesn't feel right to have everything public so that anything can change an objects location for example.