Mike Simmons wrote:Well, I like regex and Scanner, but I don't see a big advantage here. For testing I'd just write a method that takes a String as input, and I can easily call it with any String input I want. Also, how do you apply a regex to an InputStream? The two ways I can think of are to use a Scanner, or read the InputStream into a String, neither of which sounds like what you're talking about. Maybe I'm overlooking a method here?
I guess it's back to one of my pet peeves: not providing the developer with sufficient flexibility. You may have seen my rant a while back about methods that return booleans when in fact one that returns an index might make a better building block. Or indeed,
provide both. (I lost BTW; at least in terms of votes )
My objection to
parseInt() is that it forces developers into the all or nothing paradigm of Exceptions; and perhaps this is where we disagree.
Before
Scanner (which actually implements '
hasNext...()' pretty much the way I would expect - ie, by using regexes),
parseInt() forced you into a world where
any anomaly involved an Exception - and therefore a possibly significant performance hit if, in terms of
your program, the error is normal and recoverable.
I notice that quite a few things have been changed in v7 to optionally NOT throw Exceptions, which suggests to me that perhaps other people are coming around to my way of thinking (although I'm certainly not counting my
chickens yet ) and numeric parsing would seem like a prime candidate. So, you get an invalid string - substitute a pre-determined "invalid" value; or, if it's an
Integer, null - and
let the developer decide what to do with it.
Personally, I'd be happy to have a method that can parse any
int except Integer.MIN_VALUE, using it as an "INVALID", and throws an exception in the
specific case where its handed "-2147483648". However, given the amount of time it takes to parse a String anyway, why not just hand back an
Integer (or null)?
Winston