I am studying programming and although I feel like I have good knowledge in programming (been writing PHP, Javascript etc for years), I’ve never dived into the world of OOP. Because of this I am asking for a general answer for the situation I am in. I know that there always will be some exceptions, but I am looking for the most correct approach in this case.
Ok, so I have two classes, Game and GameGraphics. GameGraphics will create an object of Game and use all the methods it has. We recently learned that all variables a class should be private, so all the variables in Game are accessed by GameGraphics through getters and setters.
But, when I want to access the variables of Game inside the Game class, should I use the public methods, or just access the variables directly? What is the most correct approach to this?
I’m developing in Java, if that matters. And please excuse my lack of OOP-experience.
The two major reasons behind using accessor methods (getters and setters) to access variables of other classes are
A slight drop in readability is a reasonable price to pay for these advantages, because they let you encapsulate the logic of your class, resulting in tighter control on your part.
Neither of these advantages applies when it comes to private methods: they cannot implement interface methods, and they cannot be overridden. In fact, Java compiler would often optimize them out altogether, especially the simpler ones.
That is why I would recommend going straight for the instance variables, rather than adding an extra layer that does not help readability, yet gets optimized out by the compiler.