Versions Compared

Key

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

...

Classes and class members must be given the minimum possible access so that malicious code has the least opportunity to compromise security. As far as possible, classes should avoid exposing methods that contain (or invoke) sensitive code through interfaces; interfaces allow only publicly accessible methods, and such methods are part of the public application programming interface (API) of the class. (Note that this is the opposite of Joshua Bloch's recommendation to prefer interfaces for APIs [Bloch 2008, Item 16].) One exception to this is implementing an unmodifiable interface that exposes a public immutable view of a mutable object. (See OBJ04-J. Provide mutable classes with copy functionality to safely allow passing instances to untrusted code.) Additionally, note that even if a nonfinal class's visibility is default, it can be susceptible to misuse if it contains public methods. Methods that not only perform all necessary security checks, but also sanitize all inputs, may be exposed through interfaces.

...

For any given body of code, we can compute the minimum accessibility for each class and member so that we do not introduce new compilation errors. The limitation is that the result of this computation may lack any resemblance to what the designer intended when the code was written. For example, unused members can obviously be declared to be private. However, such members could be unused only because the particular body of code examined coincidentally lacks references to the members.

Related Guidelines

...

[Bloch 2008]

Item 13, "Minimize the Accessibility of Classes and Members"
Item 16, "Prefer Interfaces to Abstract Classes"

[Campione 1996]

Access Control

[JLS 2011]

§6.6, "Access Control"

[McGraw 1999]

Chapter 3, "Java Language Security Constructs"

...