Same value tested against both double and int
ID |
dart.portability.avoid_double_and_int_checks |
Severity |
low |
Remediation Complexity |
medium |
Remediation Risk |
medium |
Remediation Effort |
low |
Resource |
Platform Portability |
Language |
Dart |
Description
Reports a value tested against both double and int - an if/else if chain whose two branches check the same operand, or the two checks joined with ||.
Rationale
Web builds compile every Dart number to a JavaScript double, so int and double are the same runtime representation there and a whole number satisfies both tests. 1.0 is int is false on the VM and true on the web, which makes the branch that is taken depend on the compilation target: code tested on a device takes one path and the same code in the browser takes the other. The failure is quiet, because both branches typically produce a number and only the formatting or the rounding differs.
The following code illustrates the pattern detected by this rule:
String describe(Object value) {
// FLAGGED: Same value tested against both double and int
if (value is double) {
return 'double';
} else if (value is int) {
return 'int';
}
return 'other';
}
Remediation
Test for num when the distinction does not matter, which is the common case. Where it does, branch on a property of the value rather than on its declared type - compare against value.truncateToDouble(), or use value % 1 == 0 - so that the same code answers the same way on every platform.