...
This noncompliant code example shows how side effects in expressions can lead to unanticipated outcomes. The programmer intends to write access control logic based on different threshold levelsthresholds. Each user has a rating that must be above the threshold to be granted access. As shown, a simple method can calculate the rating. The get()
method is expected to return a non-zero factor value for authorized users who are authorized and a zero value for those who are unauthorized users.
In this case, the programmer expects the rightmost subexpression to evaluate The programmer in this example incorrectly assumes that the rightmost subexpression is evaluated first because the *
operator has a higher precedence than the +
operator . The parentheses reinforce this belief. These ideas lead and because the subexpression is parenthesized. This leads to the incorrect conclusion that the right-hand side evaluates to zero whenever the get()
method returns zero. The programmer expects number
to be that number
is assigned 0 because of the rightmost number = get()
subexpression. Consequently, the test in the left-hand subexpression is expected to reject the unprivileged user because the rating value (of number
) is below the threshold of 10
.
...
Code Block | ||
---|---|---|
| ||
class BadPrecedence {
public static void main(String[] args) {
int number = 17;
int[] threshold = new int[20];
threshold[0] = 10;
number = (number > threshold[0] ? 0 : -2)
+ ((31 * ++number) * (number = get()));
// ...
if (number == 0) {
System.out.println("Access granted");
} else {
System.out.println("Denied access"); // number = -2
}
}
public static int get() {
int number = 0;
// Assign number to non zero value if authorized else 0
return number;
}
}
|
...