Question

Since myObject.toString() fails when myObject is null (throws a NullPointerException), it is safer to do myObject+"", since it's essentially doing String.valueOf(myObject).concat(""), which doesn't fail, but would instead result in the String "null".

However, is this a good practice? My first thought is that it seems like it might take longer to perform, since it's implicitly calling two methods, but it does help guarantee software that doesn't crash.

Était-ce utile?

La solution

You certainly can do myObject+"". But as you already know, that requires some extra method invocation. That will depend upon the application you're using it in. Will that extra method invocation be a bottle-neck for the application? I guess that is rarely an issue. Or, to avoid that extra method call, you can directly use String#valueOf() method. But that would depend upon how you want to handle nulls. I would certainly not proceed normally in these circumstances. At least log a message indicating null reference.

Also, if you're already on Java 7, then you can use Objects.toString(Object) method, that handles null for you. Again, that method returns "null" for null references.

So, now it's your call. I've given you some option. You might want to throw exception, log message and proceed with "null" string, or some default string like "".

Autres conseils

If you want that behavior, String.valueOf(myObject) gets you the same while being less hacky. But it also means that a null string and the string "null" are treated the same. It's usually better to check for null values explicitly, unless you're just print to a log or such. But in those cases, most methods take an Object reference and handle nulls for you (e.g. System.out.println, most logging frameworks, etc.)

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top