What is the best alternative to null in object ori

2019-04-26 20:50发布

问题:

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?

回答1:

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.



回答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.



回答3:

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



标签: oop object