What is the best alternative to null in object ori

2019-04-26 20:18发布

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?

标签: oop object
3条回答
三岁会撩人
2楼-- · 2019-04-26 20:47

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.

查看更多
Melony?
3楼-- · 2019-04-26 20:49

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.

查看更多
欢心
4楼-- · 2019-04-26 20:51

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

查看更多
登录 后发表回答