Search code examples
javaguavapreconditions

How to interpret string as a negative number or zero and throw IAE accordingly?


I have a method in which I am accepting a String and that can be number as a string or a normal string.

public Builder setClientId(String clientId) {
    checkNotNull(clientId, "clientId cannot be null");
    checkArgument(clientId.length() > 0, "clientId can't be an empty string");
    this.clientId = clientId;
    return this;
}

Now I want to add a check let's say if anyone is passing clientId as negative number "-12345" or zero "0", then I want to interpret this and throw IllegalArgumentException with message as "clientid must not be negative or zero as a number" or may be some other good message. How can I do this using guava Preconditions if possible?

As per suggestion I am using below code:

public Builder setClientId(String clientId) {
    checkNotNull(clientId, "clientId cannot be null");
    checkArgument(clientId.length() > 0, "clientId can't be an empty string");
    checkArgument(!clientid.matches("-\\d+|0"), "clientid must not be negative or zero");
    this.clientId = clientId;
    return this;
}

Is there any better way of doing it?


Solution

  • I think the simplest way of doing this is as follows:

     public Builder setClientId(String clientId) {
        final Integer id = Ints.tryParse(clientId);
        checkArgument(id != null && id.intValue() > 0,
          "clientId must be a positive number, found: '%s'.", clientId);
        this.clientId = clientId;
        return this;
      }
    

    When calling this method, this gives:

    .setClientId("+-2"); 
    // java.lang.IllegalArgumentException: clientId must be a positive number, found: '+-2'.
    
    .setClientId("-1"); 
    // java.lang.IllegalArgumentException: clientId must be a positive number, found: '-1'.
    
    .setClientId(null); 
    // java.lang.NullPointerException
    

    This code uses Ints.tryParse. From the JavaDoc:

    Returns:

    the integer value represented by string, or null if string has a length of zero or cannot be parsed as an integer value

    Also, it throws a NullPointerException when a null is received.


    Edit: however, if any other string is allowed, the code changes to:

    public Builder setClientId(String clientId) {
        checkArgument(!Strings.isNullOrEmpty(clientId),
          "clientId may not be null or an empty string, found '%s'.", clientId);
        final Integer id = Ints.tryParse(clientId);
        if (id != null) {
          checkArgument(id.intValue() > 0,
            "clientId must be a positive number, found: '%s'.", clientId);
        }
        this.clientId = clientId;
        return this;
      }
    

    This code will accept all strings that are either a strictly positive integer OR non-null and non-empty.