1

When I'm creating instances of domain objects from a ResultSet, should I convert Strings which are null to an empty String. Conversely, when writing to the database should empty Strings be converted to null Strings?

What's best practise here? Or is it just dependent on the application?

Many thanks.

aioobe
  • 413,195
  • 112
  • 811
  • 826
mip
  • 1,886
  • 8
  • 26
  • 32

2 Answers2

2

The empty string, "" is a string just as any other. To me it, storing "" as NULL makes as much sense as storing "" as '' and storing "abc" as NULL.

So, keep things simple: Store "" as '', and store a null reference as NULL.


To quote the MySQL reference manual:

The concept of the NULL value is a common source of confusion for newcomers to SQL, who often think that NULL is the same thing as an empty string ''.

aioobe
  • 413,195
  • 112
  • 811
  • 826
  • Thanks @aioobe. Yes, that's my thinking too though though this will lead to lots of "if != null". – mip Feb 07 '12 at 10:39
2

IMO, you should keep nulls as nulls. Depending on your DB schema, empty string and null are two distinct values. If you conflate those values, your code may produce unexpected results -- especially if you have multiple developers working on the same code base. You may have to account for both cases in downstream code, but that will most likely be clearer and more maintainable/testable.

artgon
  • 714
  • 1
  • 6
  • 9