Public fields in public classes do not respect the encapsulation principle and have three main disadvantages:
- Additional behavior such as validation cannot be added.
- The internal representation is exposed, and cannot be changed afterwards.
- Member values are subject to change from anywhere in the code and may not meet the programmer’s assumptions.
To prevent unauthorized modifications, private attributes and accessor methods (set and get) should be used.
What is the potential impact?
Public fields can be modified by any part of the code and this can lead to unexpected changes and hard-to-trace bugs.
Public fields don’t hide the implementation details. As a consequence, it is no longer possible to change how the data is stored internally without
impacting the client code of the class.
The code is harder to maintain.
Exceptions
This rule ignores public final
fields because they are not modifiable. Also, annotated fields, whatever the annotation(s) will be
ignored, as annotations are often used by injection frameworks, which in exchange require having public fields.