Java Reference
In-Depth Information
double area(double radius) {
return Math.PI * radius * radius;
}
double volume(double radius) {
return 4.0/3.0 * Math.PI * radius * radius * radius;
}
double greatCircleCircumference(double radius) {
return 2 * Math.PI * radius;
}
Noncompliant Code Example
Thisnoncompliantcodeexampledefinesaconstant
BUFSIZE
,butthendefeatsthepurpose
ofdefining
BUFSIZE
asaconstantbyassumingaspecificvaluefor
BUFSIZE
inthefollow-
ing expression:
private static final int BUFSIZE = 512;
// ...
public void shiftBlock() {
int nblocks = 1 + ((nbytes - 1) >> 9); // BUFSIZE = 512 = 2
^
9
// ...
}
Theprogrammerhasassumedthat
BUFSIZE
is512,andright-shifting9bitsisthesame
(for positive numbers) as dividing by 512. However, if
BUFSIZE
changes to 1024 in the
future, modifications will be difficult and error prone.
This code also fails to conform to
The CERT
®
Oracle
®
Secure Coding Standard for
Java
™
[Long2012],“NUM01-J.Donotperformbitwise andarithmetic operations onthe
same data.” Replacing a division operation with a right shift is considered a premature
optimization. Normally, the compiler will do a better job of determining when this optim-
ization should be performed.