banabella
banabella

Reputation: 39

NULL vs Empty String usage

I have been wondering recently about usage of empty string vs null.

I know what these values mean, but I wonder when I should use each? It is not about exact programming language or approach.

Upvotes: 1

Views: 1280

Answers (2)

Iason
Iason

Reputation: 382

Moste of the time you want to prevent both. The difference is that a null value is returned most of the time when you try to use a variable which doesn't exist or has not been instantiated by you or the programm. The empty string is most of the time a human approach of emptying a variable which already exists.

Upvotes: 1

J L
J L

Reputation: 987

As a general guideline, I avoid using null no matter what.

null is not an object, it can't do anything and you can't expect anything from it. It will evenatually leak as a rather obscure NullPointerException. You can't access any field or any method in null and trying to do so, will lead you to the aforementioned excpetion.

You can avoid using it with:

  • Null Object pattern
  • Raising Exception with a more useful than message than an empty NullPointerException
  • Designing your classes to have its fields private final therefore avoiding nulls by design

Upvotes: 2

Related Questions