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:
That's pretty much it, although returning MIN_VALUE is kind of questionable, unless you're sure it's the right thing to use for what you're essentially using as an error code. At the very least I'd document the error code behavior, though.
Might also be useful (depending on the application) to log the bad input so you can trace.
You could use a Integer, which can be set to null if you have a bad value. If you are using java 1.6, it will provide auto boxing/unboxing for you.
I'm sure it is bad form, but I have a set of static methods on a Utilities class that do things like Utilities.tryParseInt(String value)
which returns 0 if the String is unparseable and Utilities.tryParseInt(String value, int defaultValue)
which allows you to specify a value to use if parseInt()
throws an exception.
I believe there are times when returning a known value on bad input is perfectly acceptable. A very contrived example: you ask the user for a date in the format YYYYMMDD and they give you bad input. It may be perfectly acceptable to do something like Utilities.tryParseInt(date, 19000101)
or Utilities.tryParseInt(date, 29991231);
depending on the program requirements.
Put some if statements in front of it. if (null != userdata )
I think the best practice is the code you show.
I wouldn't go for the regex alternative because of the overhead.
What's the problem with your approach? I don't think doing it that way will hurt your application's performance at all. That's the correct way to do it. Don't optimize prematurely.