I am writing a game and I have a class for the input which contains booleans for all the different keys. I create an instance of this class in the main game class. Is it ok for the booleans to be public, or should I access them with accessors?
Share
Instead of having a
booleanfor each key, it would be more readable and easier to code if you had aprivate Map<String, Boolean> keyStates, with all keys initialized tofalse. Then your accessors might be:The general reason for having accessor methods rather than public variables is that it allows the class to change its implementation without requiring changes in the classes that interact with its members. For example, with the above, you can now add code to count or log key presses, or change the underlying type of
Mapused, without exposing any of this to the outside.This is not personal preference. Encapsulation and Interfaces are integral parts of OO Software Engineering, and are the primary design reasons that the Internet is possible from a technical POV.