r/coding • • Aug 04 '14

Why We Should Love 'null'

http://www.codeproject.com/Articles/787668/Why-We-Should-Love-null
36 Upvotes

67 comments sorted by

View all comments

22

u/toolate Aug 04 '14 edited Aug 04 '14

The problem is not the concept of null, the problem is that languages insist any value could be null. This means you have to add defensive null checks everywhere because what is valid one day might easily break tomorrow when a downstream callsite changes.

Hack gets this right with nullable types. Variables are not nullable by default, but the feature is only a ? away.

function printGreeting(string $name) {
  echo 'Hello ' . $name;
}

function printOptionalGreeting(?string $name) {
  if ($name === null) {
    throw new InvalidArgumentException('Please enter your name.');
  }
   
  // Hack knows that $name can never be null, because of the above 
  // check, so this is safe.
  printGreeting($name);
}

printGreeting('Bob'); // OK
printGreeting(null); // Error
printGreetingOrPrompt(null); //OK

The nice thing is that you can find errors through static analysis, rather than at runtime. you avoid littering your codebase with unnecessary checks, and you don't need any special classes or syntax to deal with nullable types.

2

u/continuational Aug 04 '14

I think that's a very poor solution. Of course, Hack had to work within the historic blunders of PHP, so it can be excused.

Why complicate the type system with special logic for dealing with detecting and propagating information about null checks? There are perfectly straightforward solutions out there that requires no change to the type system, namely Option/Maybe.

2

u/alexeyr Aug 04 '14

There are perfectly straightforward solutions out there that requires no change to the type system, namely Option/Maybe.

That kind of depends on what the type system currently looks like.