When using Math.min()
and Math.max()
together for bounds checking, it’s important to feed the right operands to each
method. Math.min()
should be used with the upper end of the range being checked, and Math.max()
should be
used with the lower end of the range. Get it backwards, and the result will always be the same end of the range.
Noncompliant code example
private static final int UPPER = 20;
private static final int LOWER = 0;
public int doRangeCheck(int num) { // Let's say num = 12
int result = Math.min(LOWER, num); // result = 0
return Math.max(UPPER, result); // Noncompliant; result is now 20: even though 12 was in the range
}
Compliant solution
Swapping method min()
and max()
invocations without changing parameters.
private static final int UPPER = 20;
private static final int LOWER = 0;
public int doRangeCheck(int num) { // Let's say num = 12
int result = Math.max(LOWER, num); // result = 12
return Math.min(UPPER, result); // Compliant; result is still 12
}
or swapping bounds UPPER
and LOWER
used as parameters without changing the invoked methods.
private static final int UPPER = 20;
private static final int LOWER = 0;
public int doRangeCheck(int num) { // Let's say num = 12
int result = Math.min(UPPER, num); // result = 12
return Math.max(LOWER, result); // Compliant; result is still 12
}