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 Malicious callers can manipulate such members in unintended ways, with undefined consequences. If they class members need to be exposed beyond the package their class 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.

...

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 code 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]\].

...

This noncompliant code example shows a static, mutable hash map with public accessibility.

...

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 - assuming 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.

...