Best implementation for an isNumber(string) method

前端 未结 19 2366
感动是毒
感动是毒 2020-12-15 20:04

In my limited experience, I\'ve been on several projects that have had some sort of string utility class with methods to determine if a given string is a number. The idea h

19条回答
  •  有刺的猬
    2020-12-15 20:14

    I just added this class to my utils:

    public class TryParseLong {
    private boolean isParseable;
    
    private long value;
    
    public TryParseLong(String toParse) {
        try {
            value = Long.parseLong(toParse);
            isParseable = true;
        } catch (NumberFormatException e) {
            // Exception set to null to indicate it is deliberately
            // being ignored, since the compensating action
            // of clearing the parsable flag is being taken.
            e = null;
    
            isParseable = false;
        }
    }
    
    public boolean isParsable() {
        return isParseable;
    }
    
    public long getLong() {
        return value;
    }
    }
    

    To use it:

    TryParseLong valueAsLong = new TryParseLong(value);
    
    if (valueAsLong.isParsable()) {
        ...
        // Do something with valueAsLong.getLong();
    } else {
        ...
    }
    

    This only parses the value once.

    It still makes use of the exception and control flow by exceptions, but at least it encapsulates that kind of code in a utility class, and code that uses it can work in a more normal way.

    The problem with Java versus C#, is that C# has out values and pass by reference, so it can effectively return 2 pieces of information; the flag to indicate that something is parsable or not, and the actual parsed value. When we reutrn >1 value in Java, we need to create an object to hold them, so I took that approach and put the flag and the parsed value in an object.

    Escape analysis is likely to handle this efficiently, and create the value and flag on the stack, and never create this object on the heap, so I think doing this will have minimal impact on performance.

    To my thinking this gives about the optimal compromise between keeping control-flow-by-exception out your code, good performance, and not parsing the integer more than once.

提交回复
热议问题