aspose file tools*
The moose likes Java in General and the fly likes null or an empty String for Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "null or an empty String for "optional" data members" Watch "null or an empty String for "optional" data members" New topic
Author

null or an empty String for "optional" data members

Salman Ahmed
Greenhorn

Joined: Mar 18, 2008
Posts: 27
I have a Java class that models a business domain object. This business domain object has a number of fields that are represented as String-valued data members in the corresponding class. Some of those String-valued fields are not present in some object instances.

Is it better to model such a non-existent (or non-available) field as having an empty String value ("") or should I set it to null?

I've been thinking of this issue in reference to Item #27 from "Effective Java" where Bloch correctly recommends that empty Collections should be returned instead of returning null.

I am just wondering whether the same recommendation should be applicable for simple object types such a String-valued data member.

Would love to hear the thoughts of the more enlightened and experienced minds on JavaRanch...

Thanks.
Amir Alagic
Ranch Hand

Joined: Mar 21, 2006
Posts: 65
I would rather use empty String value (""). Didn't see your code but I guess it can help you to avoid possible NullPointerException(s).

If you, always, use always String instead of null you can in your code just check for String length for your field and don't have to write additional check for null value...
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: null or an empty String for "optional" data members