Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best alternative to null in object oriented programming?

Tags:

object

oop

I don't feel satisfied by avoiding null in OOP. Is there any alternative solution? I don't like to avoid it in this way either.

What is the best possible way to handle it?

like image 504
Madhav Bhattarai Avatar asked Dec 10 '14 07:12

Madhav Bhattarai


2 Answers

Java 8 has the new Optional type which is what I think you are asking about

A container object which may or may not contain a non-null value. If a value is present, isPresent() will return true and get() will return the value.

like image 52
Elliott Frisch Avatar answered Sep 29 '22 12:09

Elliott Frisch


Although you don't like it, the Null Object Pattern is one of the best ways to avoid null. Also never return null when you could return an empty list.

like image 41
Tom Jonckheere Avatar answered Sep 29 '22 13:09

Tom Jonckheere