简体   繁体   中英

Should I use null or empty string if the String is passed around in the code? (Java best practice)

I have a String which is optional in the API. If I don't get that parameter I am unsure if I should use an empty String or a null value. The value is being passed around in a lot of functions and being used in some of them.

I have been thinking about this and this is what I came up with.

  • Using null could be better because it would throw NPE if a developer tries to use it without checking if it exists. "" would not do that so the developer may think he is using the string when it does not exist.
  • Using "" could be better because if a developer wants to change something he/she won't need to check for null pointer. This could be beneficial when the developer does not need to know if the value exist like changing the encoding of the string.

What is the best practice in such a situation?

EDIT: I am looking for reasons why an approach is better than the other. And Optional sounds interesting.

Empty string definitely is better than null. If you want to indicate that the setting is optional , and provide a different behavior, use Optional<String> .

In my opinion, if "" is not a valid value for that parameter, use "" . Otherwise use null .

Regarding your first point, you'll get an IndexOutOfRangeException if you try to substring an empty string or call charAt or anything like that. So I don't think it's gonna encourage using it without checking for empty string. And there are lots of ways you get prevent an NPE.

An alternative is Optional<String> , but I think currently it's syntax looks too ugly. I would still use "" if it is not considered a valid value.

If you're returning a null String in your API, it is entirely possible that the developer consuming it will forget to check that its value is null . As Joop has already mentioned in his answer, use Optional<String> .

This forces the consumer of the API to check for its existence (or at the very least, think about how to handle its absence), eg

myAPI.ifPresent(/* do something with String */);
myAPI.map(String::toLowerCase).orElse("");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM