42 lines
1.5 KiB
Plaintext
42 lines
1.5 KiB
Plaintext
![]() |
When using <code>Math.min()</code> and <code>Math.max()</code> together for bounds checking, it's important to feed the right operands to each method. <code>Math.min()</code> should be used with the *upper* end of the range being checked, and <code>Math.max()</code> 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 <code>min()</code> and <code>max()</code> 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 <code>UPPER</code> and <code>LOWER</code> 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
|
||
|
}
|
||
|
----
|
||
|
|