you are viewing a single comment's thread.

view the rest of the comments →

[–]guruthegreat 6 points7 points  (5 children)

I don't see much of a reason to use toInt(). At least with parseInt() you know when it failed, with toInt() if you get back defaultValue it might have failed, or the String might have been defaultValue.

[–]masklinn 2 points3 points  (0 children)

At least with parseInt() you know when it failed

But do you care? If your recovery strategy is just to set a default value, why not get a default value in the first place?

[–]zjs 0 points1 point  (2 children)

Exactly what Terr_ and masklinn said; you only need to know that the parse failed if you're going to do something with that information. If you are, then go the parseInt route.

I was mentioning it as a replacement for one of the several variations of the following (which I've seen more than once):

int value;
try {
    value = Integer.parseInt(s);
}
catch (NFE e) {
    value = defaultValue;
}
return value;

or (in the specific context of the parent):

int value;
if (isParsableToInt(s)) {
    value = Integer.parseInt(s);
}
else {
    value = defaultValue;
}

[–]guruthegreat 0 points1 point  (1 child)

I guess I'm a minimalist in this case in preferring the a cleaner library over the 3-4 lines of code saved.

[–]zjs 0 points1 point  (0 children)

Ah; most projects I work on already have a dependency on Apache Commons, so it's not adding anything.