• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

null or an empty String for "optional" data members

 
Salman Ahmed
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic