Should I always use private access modifier for class fields?

We are currently running checkstyle in our code base and will run any fields of a non-static class that do not use private .

Is this a valid check rule, or are there situations where it is desirable to have non-private fields? For example, I thought the reason JUnit test cases were created in one package was such that they could access fields using the default access modifier?

+6
java checkstyle
source share
6 answers

One of the main features of object-oriented programming is the hiding / encapsulation of information. This means that the class allows access to member variables only through the interface: getter and setter methods. Thus, other classes cannot access member variables and modify them in an undesirable way. Checkstyle rule is valid

+7
source share

Point 13 Effective Java 2nd: Minimize the accessibility of classes and members.

Check this. It gives great ideas.

+6
source share

IMHO. It is best to make private and final fields where possible. However, for unit tests, it can be a pragmatic choice to make them private or accessible through them through reflection. (Which is the same thing)

You can also use the black box approach, which means that if you cannot determine what happened using the public method, you should not test it. (Or your tests should be more far-fetched)

+5
source share

Private access or termination is not a problem for advanced rigged frameworks such as JMockit. However, getter / setter may have some performance penny on android versions andlder

+2
source share

In general, it makes sense to use private fields, but there are exceptions to the rule. One possible exception is where you are dealing with data transfer objects (DTOs) and you want to clearly tell the client that setting the property value will not lead to a change to the backend. Public fields are a great way to report this.

+1
source share

I think this is the right correct rule to ensure that information is correctly hidden - which is an important aspect of OOP.

Instead, use the public getter and setter methods, where the object can manage changes in its state.

0
source share

All Articles