Public class variable fields do not respect the encapsulation principle and has 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.
By using private attributes and accessor methods (set and get), unauthorized modifications are prevented.
Noncompliant Code Example
public class MyClass {
public static final int SOME_CONSTANT = 0; // Compliant - constants are not checked
public String firstName; // Noncompliant
}
Compliant Solution
public class MyClass {
public static final int SOME_CONSTANT = 0; // Compliant - constants are not checked
private String firstName; // Compliant
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
}
Exceptions
Because they are not modifiable, this rule ignores public final
fields. 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.
See