2023-05-03 11:06:20 +02:00
== Why is this an issue?
2021-01-27 13:42:22 +01:00
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.
2020-06-30 12:48:39 +02:00
2023-05-03 11:06:20 +02:00
=== Noncompliant code example
2020-06-30 12:48:39 +02:00
2022-02-04 17:28:24 +01:00
[source,text]
2020-06-30 12:48:39 +02:00
----
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
}
----
2023-05-03 11:06:20 +02:00
=== Compliant solution
2020-06-30 12:48:39 +02:00
2021-01-27 13:42:22 +01:00
Swapping method ``++min()++`` and ``++max()++`` invocations without changing parameters.
2020-06-30 14:49:38 +02:00
2022-02-04 17:28:24 +01:00
[source,text]
2020-06-30 12:48:39 +02:00
----
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
}
----
2021-01-27 13:42:22 +01:00
or swapping bounds ``++UPPER++`` and ``++LOWER++`` used as parameters without changing the invoked methods.
2020-06-30 12:48:39 +02:00
2021-02-02 15:02:10 +01:00
2022-02-04 17:28:24 +01:00
[source,text]
2020-06-30 12:48:39 +02:00
----
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
}
----