开发者

Should I always use the private access modifier for class fields?

开发者 https://www.devze.com 2023-02-20 14:05 出处:网络
Currently we are running checkstyle on our code base and it flags up any non-static class fields th开发者_Python百科at don\'t use the private access modifier.

Currently we are running checkstyle on our code base and it flags up any non-static class fields th开发者_Python百科at 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?


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


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

Check this out. It gives great ideas.


IMHO Its best to make fields private and final where ever possible. For unit tests however, it may be a pragmatic choice to make them package-private or access them via reflection. (Which amounts to the same thing)

You can also take the approach of black-box testing which means unless you can determine what has happened via a public method, it shouldn't be tested. (Or your tests need to be more contrived)


Private access or finality is not a problem for advanced mocking frameworks like JMockit. However, getter/setter may have some performance penatly on onlder versions of android


In general it makes sense to use private fields but there are exceptions to the rule. One possible exception is where you're dealing with data transfer objects (DTOs) and you want to communicate clearly to the client that setting the value of a property will not produce a change on the backend. Public fields are a nice way of communicating that.


I think it is a good valid rule that ensures information hiding is being done correctly - which is an important facet of OOP.

Use Public getter and setter methods instead where the object can control changes to its state.

0

精彩评论

暂无评论...
验证码 换一张
取 消