Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it bad to have public variables in a non-static class?

Tags:

java

input

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?

like image 335
user1150769 Avatar asked Mar 12 '12 16:03

user1150769


People also ask

Should static variables be public or private?

Static variables are created when the program starts and destroyed when the program stops. Visibility is similar to instance variables. However, most static variables are declared public since they must be available for users of the class.

Are public static variables bad?

Static variables are generally considered bad because they represent global state and are therefore much more difficult to reason about. In particular, they break the assumptions of object-oriented programming.

Are public static methods bad?

Static methods are bad for testability. Since static methods belong to the class and not a particular instance, mocking them becomes difficult and dangerous. Overriding a static method is not that simple for some languages.

Can I have static variable in non-static class?

"Can a non-static method access a static variable or call a static method" is one of the frequently asked questions on the static modifier in Java, the answer is, Yes, a non-static method can access a static variable or call a static method in Java.


1 Answers

Instead of having a boolean for each key, it would be more readable and easier to code if you had a private Map<String, Boolean> keyStates, with all keys initialized to false. Then your accessors might be:

public void setPressed(String keyName) {
    keyStates.put(keyName, true);
}

public void setReleased(String keyName) {
    keyStates.put(keyName, false);
}

public boolean isPressed(String keyName) {
    return keyStates.get(keyName);
}

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 Map used, 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.

like image 175
calebds Avatar answered Sep 24 '22 19:09

calebds