Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

If data members are declared public or protected, it is difficult to control how they are accessed. It is possible that they can be manipulated in unintended ways, with undefined consequences. If they need to be exposed beyond the package their class they are is declared in, acceessor methods may be used. Also, with the use of setter methods, modification of data members can be monitored as appropriate (e.g., by defensive copying, validating input, logging and so on). Methods that are declared public or protected must preserve the invariants of the class and their use should not be abused.

Noncompliant Code Example

Wiki Markup
In this noncompliant code example, the data member {{total}} is meant to keep track of the total number of elements as they are added and removed from a container. However, as a {{public}} data member, {{total}} can be altered by external code, independent of these actions. This noncompiant example violates the condition that {{public}} classes must not expose data members by declaring them {{public}}. It is a bad practice to expose both mutable as well as immutable fields from a {{public}} class \[[Bloch 08|AA. Java References#Bloch 08]\].

Code Block
bgColor#FFCCCC
public class Widget {
  public int total;
  void add (SomeType someParameter) {
    total++;
    // ...
  }
  void remove (SomeType someParameter) {
    total--;
    // ...
  }
}

...

This compliant solution declares total as private and provides a public accessor so that the class can be accessed beyond the current package. The method add() modifies its value without violating any class invariants.

Code Block
bgColor#ccccff
public class Widget {
  private int total;
  void add (someType someParameter) {
    total++;
    // ...
  }
  void remove (someType someParameter) {
    total--;
    // ...
  }
  public int getTotal () {
    return total;
  }
}

...

One example of appropriate public instance variables is the case where the class is essentially a data structure, with no behavior. In other words, if you would have used a struct instead of a class (if Java supported struct), then it's appropriate to make the class's instance variables public.

Wiki Markup
*EX2:* "if a class is package-private or is a private nested class, there is
nothing inherently wrong with exposing its data fields - assumng they do an adequate job of describing the abstraction provided by the class. This approach
generates less visual clutter than the accessor-method approach, both in the class
definition and in the client code that uses it." \[[Bloch 08|AA. Java References#Bloch 08]\]. This exception applies to both mutable as well as immutable fields.

Risk Assessment

Failing to declare data members private can break encapsulation.

...