Why NULL references are a bad idea

Returning NULL when the object is unavaliable increase the complexity of function. The function can return an empty object or empty array instead of NULL.

But NULL is still useful to represent the third state “unknown” other than “yes” and “no”

Why NULL references are a bad idea

1
2
3
4
5
6
7
8
9
class BurgerRepository {
public function get($id) {
$burger = $this->db->query(...);
if (!$burger) {
return NULL;
}
return new Burger($burger);
}
}

If NULL reference is used user, need to check the return value everytime

1
2
3
4
$burger = $burgerRepository->get(10);
if($burger) {
$customer->eat($burger);
}

If you don’t mind the logic flow is broke, we can throw error directly. Burger can not be null, but there a “no burger” error make sense.

1
2
3
4
5
6
7
8
9
class BurgerRepository {
public function get($id) {
$burger = $this->db->query(...);
if (!$burger) {
throw new BurgerOutOfStockException;
}
return new Burger($burger);
}
}

For some case, returning an empty object / array is also a good choice

1
2
3
4
5
6
7
8
9
class BurgerRepository {
public function getAll() {
$burgers = $this->db->query(...);
if (!$burgers) {
return [];
}
return $burgers;
}
}