Java Reference
In-Depth Information
Java [Long 2012], “OBJ04-J. Provide mutable classes with copy functionality to safely
allow passing instances to untrusted code.”) Note that even if a nonfinal class's visibil-
ity is default, it can be susceptible to misuse if it contains public methods. Methods that
perform all necessary security checks and sanitize all inputs may be exposed through in-
terfaces.
Protected accessibility is invalid for non-nested classes, but nested classes may be de-
clared protected. Fields ofnonfinal public classes should rarely bedeclared protected; un-
trusted code in another package can subclass the class, and access the member. Further-
more, protected members are part of the API of the class, and consequently require con-
tinued support. When this rule is followed, declaring fields as protected is unnecessary.
“OBJ01-J. Declare data members as private and provide accessible wrapper methods”
[Long 2012] recommends declaring fields as private.
If a class, interface, method, or field is part of a published API, such as a web service
endpoint, it may be declared public. Other classes and members should be declared either
package-private or private. For example, non-security-critical classes are encouraged to
provide public static factories to implement instance control with a private constructor.
Noncompliant Code Example (Public Class)
This noncompliant code example defines a class that is internal to a system and not part
of any public API. Nonetheless, this class is declared public.
Click here to view code image
public final class Point {
private final int x;
private final int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public void getPoint() {
System.out.println("(" + x + "," + y + ")");
}
}
Even though this example complies with “OBJ01-J. Declare data members as private
and provide accessible wrapper methods” [Long 2012], untrusted code could instantiate
Point and invoke the public getPoint() method to obtain the coordinates.
Search WWH ::




Custom Search