The billion dollar mistake
Tony Hoare
- 1965 - Invented "null"
- 2009 - Called it his "billion dollar mistake"
function getFerrari() {}
function getFerrari(): Ferrari {}
function getFerrari(): Ferrari {}
const myCar = getFerrari();
function getFerrari(): Ferrari {
return null;
}
const myCar = getFerrari();
function getFerrari(): Ferrari {
return null;
}
const myCar = getFerrari();
// ...
const key = myCar.getKey();
TypeError: Cannot read property 'getKey' of null
function getFerrari(): Ferrari {
return null;
}
const myCar = getFerrari();
// ...
const key: Key;
if (myCar === null)
key = null;
else
key = myCar.getKey();
function getFerrari(): Ferrari {
return null;
}
const myCar = getFerrari();
// ...
const key = myCar && myCar.getKey();
The problem with null
Can hide in any form
Any value could be null
Hard to debug
The Alternative
function getFerrari(): Ferrari {
return null;
}
function getFerrari(): Ferrari {
return new F40();
}
function getFerrari(): Ferrari {
return null;
}
function getFerrari(): Maybe<Ferrari> {
return null;
}
New Rules
- Cannot use null
- If a value can be null, use Maybe type
Arrays
function getFerraris(): Array<Ferrari> {
// ...
}
function getFerraris(): Array<Ferrari> {
// ...
}
const myFerraris = getFerraris();
function getFerraris(): Array<Ferrari> {
// ...
}
const myFerraris = getFerraris();
const key = myFerraris.getKey();
function getFerraris(): Array<Ferrari> {
// ...
}
const myFerraris = getFerraris();
const key = myFerraris.getKey();
function getFerraris(): Array<Ferrari> {
// ...
}
const myFerraris = getFerraris();
const keys =
myFerraris.map(ferrari => ferrari.getKey());
function getFerraris(): Array<Ferrari> {
// ...
}
const myFerraris = getFerraris();
const keys: Array<Key> =
myFerraris.map(ferrari => ferrari.getKey());
Promises
function requestFerrari(): Promise<Ferrari> {
// ...
}
function requestFerrari(): Promise<Ferrari> {
// ...
}
const promiseOfFerrari = requestFerrari();
function requestFerrari(): Promise<Ferrari> {
// ...
}
const promiseOfFerrari = requestFerrari();
const key = promiseOfFerrari.getKey();
function requestFerrari(): Promise<Ferrari> {
// ...
}
const promiseOfFerrari = requestFerrari();
const key = promiseOfFerrari.getKey();
function requestFerrari(): Promise<Ferrari> {
// ...
}
const promiseOfFerrari = requestFerrari();
const promiseOfKey =
promiseOfFerrari.then(
ferrari => ferrari.getKey()
);
function requestFerrari(): Promise<Ferrari> {
// ...
}
const promiseOfFerrari = requestFerrari();
const promiseOfKey: Promise<Key> =
promiseOfFerrari.then(
ferrari => ferrari.getKey()
);
The billion dollar mistake
By James Morcom
The billion dollar mistake
- 719