String to Int in java - Likely bad data, need to avoid exceptions

前端 未结 16 2103
迷失自我
迷失自我 2020-12-04 18:02

Seeing as Java doesn\'t have nullable types, nor does it have a TryParse(), how do you handle input validation without throwing an exceptions?

The usual way:

16条回答
  •  日久生厌
    2020-12-04 18:37

    The above code is bad because it is equivalent as the following.

    // this is bad
    int val = Integer.MIN_VALUE;
    try
    {
       val = Integer.parseInt(userdata);
    }
    catch (NumberFormatException ignoreException) { }
    

    The exception is ignored completely. Also, the magic token is bad because an user can pass in -2147483648 (Integer.MIN_VALUE).

    The generic parse-able question is not beneficial. Rather, it should be relevant to the context. Your application has a specific requirement. You can define your method as

    private boolean isUserValueAcceptable(String userData)
    {
       return (    isNumber(userData)    
              &&   isInteger(userData)   
              &&   isBetween(userData, Integer.MIN_VALUE, Integer.MAX_VALUE ) 
              );
    }
    

    Where you can documentation the requirement and you can create well defined and testable rules.

提交回复
热议问题