Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the purpose of the empty string?

To me, as a developer and as a user, I find the empty string ("") useless and the cause of much confusion, it's like saying string == char[]

Maybe computers need the empty string, so I'd like to learn why.

See also:

  • Default string initialization: NULL or Empty?
  • Best Practice: Should functions return null or an empty object?
like image 734
Max Toro Avatar asked Mar 29 '10 20:03

Max Toro


2 Answers

Empty string are quite common in real world situations - and they are useful to differentiate from null.

  • Null means that the value is undefined or unknown.

  • An empty string means that it is known to be nothing (empty).

It might seem like splitting hairs, but there is a difference. Empty strings are instances of an object - nulls are not. You can manipulate an empty string using any of the valid methods that can be called on a string object. You cannot manipulate a null. Empty strings are often the result of certain manipulations on other strings, for example:

var source = "Hello";
var result = source.Remove("Hello");  // result is now: ""

Here's a simple example where the above matters: an application with a form that collects a persons's middle name via a textbox. Should the value of the text box be null or empty string? It's much easier to always have the textbox return an empty string as its value (when empty) rather than trying to differentiate between null and "".

Interestingly, some databases DO NOT differentiate between NULL and empty string - the best example of which is Oracle. In Oracle:

INSERT into MYTABLE(name) VALUES('')

actually inserts a NULL into the table. This can in fact create confusing situations when writing code that manipulates data from a database in .NET - you sometimes get DBNull.Value where you expected a String.

like image 188
LBushkin Avatar answered Oct 08 '22 03:10

LBushkin


Why do we need zero? It's really the same question. What is "pajama" without all the a's? "pjm". What is "a" without all the a's? "". Simple as that. The product of some string operations is a string without any characters in it, and that's the empty string. It behaves just like any other string - you can easily determine its length; you can concatenate it onto other strings, you can count the a's in it, etc.

like image 43
Carl Manaster Avatar answered Oct 08 '22 05:10

Carl Manaster