Remix.run Logo
layer8 2 hours ago

For #5, the “fix” [0] is incomplete, because you will still get a NumberFormatException when the value is out of range. For int, you could check if there are more or less than 10 digits, and use parseLong() when there are exactly 10 digits. For long, you can use BigInteger when there are exactly 18 digits. After skipping any leading zeros, of course. Or you could just replicate the JDK’s parsing implementation and change the part where it throws NumberFormatException (at the possible cost of foregoing JIT intrinsics).

A second bug is that Character.isDigit() returns true for non-ASCII Unicode digits as well, while Integer.parseInt() only supports ASCII digits.

Another bug is that the code will fail on the input string "-".

Lastly, using value.isBlank() is a pessimization over value.isEmpty() (or just checking value.length(), which is read anyway in the next line), given that the loop would break on the first blank character. It makes the function not be constant-time, along with the first point above that the length of the digit sequence isn’t being limited.

[0]

     public int parseOrDefault(String value, int defaultValue) {
        if (value == null || value.isBlank()) return defaultValue;
        for (int i = 0; i < value.length(); i++) {
            char c = value.charAt(i);
            if (i == 0 && c == '-') continue;
            if (!Character.isDigit(c)) return defaultValue;
        }
        return Integer.parseInt(value);
    }