Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Edited by NavBot (vkp) v1.0

...

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 2008|AA. Java References#BlochBibliography#Bloch 08]\].

Compliant Solution (Provide Wrappers and Reduce Accessibility of Primitive Members)

...

Wiki Markup
*OBJ00-EX1:* According to Sun's Code Conventions document \[[Conventions 2009|AA. Java References#ConventionsBibliography#Conventions 09]\]

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
*OBJ00-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 2008|AA. JavaBibliography#Bloch References#Bloch 08]\]. This exception applies to both mutable as well as immutable fields.

...

Wiki Markup
\[[JLS 2006|AA. Java References#JLSBibliography#JLS 06]\] Section 6.6, Access Control
\[[SCG 2007|AA. JavaBibliography#SCG References#SCG 07]\] Guideline 3-2 Define wrapper methods around modifiable internal state
\[[Long 2005|AA. Java References#LongBibliography#Long 05]\] Section 2.2, Public Fields
\[[Bloch 2008|AA. Java References#BlochBibliography#Bloch 08]\] Items 13: Minimize the accessibility of classes and members; 14: In public classes, use accessor methods, not public fields

...