Currently we are running checkstyle on our code base and it flags up any non-static class fields that don't use the private access modifier.
Is this a valid checkstyle rule, or are there situations where having non-private fields is desirable? For example, I thought the reason JUnit test cases are created in the same package was so that they could access fields using the default access modifier?
Private: The private access modifier is specified using the keyword private. The methods or data members declared as private are accessible only within the class in which they are declared. Any other class of the same package will not be able to access these members.
Private Access Modifier - PrivateClass and interfaces cannot be private. Variables that are declared private can be accessed outside the class, if public getter methods are present in the class. Using the private modifier is the main way that an object encapsulates itself and hides data from the outside world.
Fields should be declared private unless there is a good reason for not doing so. One of the guiding principles of lasting value in programming is "Minimize ripple effects by keeping secrets." When a field is private , the caller cannot usually get inappropriate direct access to the field.
While the public access modifier allows a code from outside or inside the class to access the class's methods and properties, the private modifier prevents access to a class's methods or properties from any code that is outside the class.
One of the main features of object orientated programming is information hiding/encapsulation. This means a class allows access to member variables only via an interface: getter and setter methods. So other classes cannot access the member variables and modify them in an unwanted way. So the checkstyle rule is valid
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With