Our project use google guava, apache commons and maybe other libraries with common tasks and I was wondering if these libraries contain methods which does null safe conversions (object to number, object to string). As for now I wrote myself some helper methods, e.g :
int parseInteger(Object obj) {
if (obj!= null) {
if (obj instanceof Integer) return (Integer) obj;
if (obj instanceof Long) return ((Long) obj).intValue();
return Integer.parseInt(obj.toString());
} else {
return 0;
}
}
I'm pretty sure there's nothing like this in Guava. As already pointed
Guava tries to force you to avoid using null wherever possible, because improper or undocumented behavior in the presence of null can cause a huge amount of confusion and bugs. I think it's definitely a good idea to avoid using nulls wherever possible, and if you can modify your code so that it doesn't use null, I strongly recommend that approach instead.
A similar argument applies to parseEverythingAsInt
. You're looking for a method accepting anything and returning an int
. The very existence of such a method encourages people to write methods returning anything. This is surely no good practice, as being strict helps to prevent errors. That's why I'm quite sure there's no such method in Guava.
Maybe my answer should better be a comment, but it's too long and I don't think there'll be a positive answer, anyway.