...
| Wiki Markup |
|---|
Classes and class members should be given 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|BB. Definitions#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 Bloch's recommendation to prefer interfaces for APIs \[[Bloch 2008|AA. Bibliography#Bloch 08], Item 16\].) One exception to this is implementing an _unmodifiable_ interface that exposes a public immutable view of a mutable object. (See guidelinerule [void SEC14-J. Provide sensitive mutable classes with unmodifiable wrappers].) Additionally, note that even if a non-final class's visibility is default, it can be susceptible to misuse if it contains public methods. Methods that perform all necessary security checks, as well as sanitizing all inputs, can also be exposed through interfaces. |
Protected accessibility is illegal for top-level classes; nested classes may be declared protected. Fields of non-final public classes should rarely be declared protected; untrusted code in another package can subclass the class and access the member. Furthermore, protected members are part of the API of the class and, thus, require continued support. When this guideline rule is followed, there is no need to declare a field as protected. The guideline rule OBJ01-J. Declare data members as private and provide accessible wrapper methods recommends declaring fields as private.
...
In this noncompliant code example, the class Point is declared public. Even though this example complies with guideline rule OBJ01-J. Declare data members as private and provide accessible wrapper methods, untrusted code could instantiate Point and invoke the public getPoint() to obtain the coordinates.
...
Because the class is final, the getPoint() method can be declared public. (A public subclass that violates this guideline rule cannot override the method and expose it to untrusted code, so its accessibility is irrelevant). For non-final classes, reducing the accessibility of methods to private or package-private eliminates this threat.
...
Search for vulnerabilities resulting from the violation of this guideline rule on the CERT website.
Related Guidelines
...