Marc Schwieterman

That depends...

Beware the Empty String

Regardless of how you feel about empty strings, you should be aware of the implications of allowing them on objects that will be persisted. While it seems reasonable to expect a database to store the exact value that you give it, that is unfortunately not always the case. If you’re going to allow empty strings on persistent objects, you should take the time to determine the behavior of the database management system you’re using. You should also assess how likely it is that you are going to either have to support multiple databases, or that you will switch to another database management system in the future.

Different database management systems handle empty strings inconsistently. Some of them will persist and later return an empty string. Others convert the empty string to a null, and some will even turn it into a single space. If you’re not aware of this behavior, you may be in for some fun debugging if the object containing the empty string is used in a set or as a map key. Values that should be unique may appear to be duplicates or just disappear. Be particularly cautious of fields used to determine object equality. Below is a table of a few database management systems and the values that they will persist when presented with an empty string.

Database Persisted Value
MySQL 5.0 Empty String
Oracle 11g Null
Sybase 15.5 Single Space

If you must or want to allow empty strings on persisted objects, you need to determine how to handle them. The main decision to make is if you will support both null and empty strings for the same value. Due to the inconsistent handling across different database management systems, you’ll need to map empty strings into a value that can be persisted reliably. If you don’t need to support null, you can use that. Otherwise you’ll need to use some magic string or an extra field. The most important thing is to be aware that this issue exists, so you don’t waste your precious time figuring out why your objects aren’t given back to you the way you left them.