Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: minor

If data members are declared public or protected, it is difficult to control how they are accessed. Malicious callers can manipulate such members in unintended ways. If class members need to be exposed beyond the package their class is declared in, wrapper accessor methods may be used. Also, with the use of wrapper methods, modification of data members can be monitored as appropriate (e.g., by defensive copying, validating input, logging and so on). The wrapper methods must preserve the invariants of the class at all times.

Noncompliant Code Example (public primitive

...

field)

In this noncompliant code example, the data member total keeps track of the total number of elements as they are added and removed from a container using the methods add() and remove(), respectively.

...

Wiki Markup
However, as a {{public}} data member, {{total}} can be altered by external code, independent of these actions. This noncompliant 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]\].

Compliant Solution (provide wrappers and reduce accessibility of primitive

...

members)

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

...