Friday, June 01, 2012

Your First Java Library Function

The first thing to do when you start creating your own library of Java functions is to write a wrapper for Integer.ParseInt() (and any of the other similar built-in functions).

Integer.ParseInt is, maybe deliberately, the most pedantic piece of code ever written.  Pass it a string like "2" and it works fine.  Pass it a string like " 2" and it goes "waoh!  A space?  What the f*ck is that?? Error!  Crash the system, we're going down!!".  Is it too much to ask to be able to handle a space?

In fact, almost any non-numeric character (the main exception being a "minus") in the string will cause it to throw a wobbly.  Even a decimal point: "2.0" is beyond its capabilities. 

My suggestion is as follows, although it's not the hardest piece of code to write:-

    public static int ParseInt(String s) {
        try {
            if (s == null) {
                s = "0";
            } else if (s.length() == 0) {
                s = "0";
            return Integer.parseInt(s.trim());
        } catch (java.lang.NumberFormatException ex) {
            return 0;

No comments: