8

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?

Community
  • 1
  • 1
Madhav Bhattarai
  • 847
  • 2
  • 10
  • 29

3 Answers3

9

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.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
2

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.

Tom Jonckheere
  • 1,630
  • 3
  • 20
  • 37
2

I favour adding a static class property of Empty. This returns a specific value for the object which can be compared against - like string.Empty in .NET

kidshaw
  • 3,423
  • 2
  • 16
  • 28