Remix.run Logo
Okx 5 hours ago

The code:

  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);
  }
Is probably worse than Integer.parseInt alone, since it can still throw NumberFormatExceptions for values that overflow (which is no longer handled!). Would maybe fix that. Unfortunately this is a major flaw in the Java standard library; parsing numbers shouldn't throw expensive exceptions.
j-vogel an hour ago | parent | next [-]

Good catches from several of you. The original fix dropped the try-catch entirely which was a regression for overflow and edge cases like a bare "-". Updated the post to keep a try-catch around the final parseInt as a safety net. The pre-validation still avoids the expensive path for the common cases, which is the core point. Appreciate the feedback.

zahlman an hour ago | parent | prev | next [-]

Not to mention it's extra work in the case where the input usually is valid.

deepsun 2 hours ago | parent | prev [-]

And it will fail with "-"