处理空对象
我已经对处理空对象的最佳方法进行了大量研究。 到目前为止,我遇到的最好的方法是使用三元运算符。
String x = object.getString1!=null?object.getString1:"";
然而我对此并不满意,因为它仍然意味着不断检查空值。 我读到的另一件事是没有返回 null 的 getter 方法,而是返回一个“Null Object”实例。 但是我不知道如何让它适用于整数/BigDecimal/等...因为它们默认保存一个值。
我也不是 100% 热衷于实现 NullObjects 的想法。还有其他人对如何处理空值有更好的了解吗?
I have done quite a bit of research on best ways to deal with null objects.
The best I came across so far is using the Ternary Operator.
String x = object.getString1!=null?object.getString1:"";
However I am not really satisfied with this since it still means constantly checking for null.
The other thing I have read about was not having getter methods that return null but returning a "Null Object" instance.
However I do not see how I could get this to work for Integers/BigDecimal/etc... since they by default hold a value.
I am not 100% keen on the idea of implementing NullObjects either. Has anyone else got a better idea of how to go about handling null's?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您的方法适合您,为什么不将其重构为静态方法并一直使用呢?
Google Guava 对字符串做了类似的事情。如果您查看 Strings 类中,您可以看到
nullToEmpty
方法,其实现如下:不要关心
@Nullable
注解。但从你的代码来看,我怀疑周围潜伏着更大的问题。 Null Integers 和 BigDecimal 表明某些地方确实不正确,您可能需要检查相关部分。将这些对象设置为 null 可能表明您应该抛出异常,但当然,这个决定取决于您。
If your approach works well for you, why not refactor it to a static method and use all the time?
Google Guava has done something similar for strings. If you take a look under the hood of Strings class, you can see the
nullToEmpty
method which is implemented like this:Don't concern yourself with the
@Nullable
annotation.But from your code, I suspect there are bigger problems lurking around. Null Integers and BigDecimal are a sign that something, somewhere isn't really right, and you might want to check the relevent parts. Having these objects set somewhere to null could be an indicator that you should be throwing an exception, but that decision is up to you, of course.
假设您使用的是 C#,您可以使用
运算符 ??
:,恕我直言,它更具可读性。
至于你的问题,我不明白使用 Null 对象模式作为值类型的意义在哪里,正如你已经指出的那样,它们不能保存空值,除非它们被声明为 Nullable,所以你将始终拥有一个有效的值 值(在语言域中有效,但在应用程序域中可能无效)。所以,这是一个完全不同的问题。
你必须对空指针做什么实际上取决于上下文,也许空对象是合适的,但如果它不可行,你应该抛出异常或者可能使用一些默认值......
Assuming you are using C#, you could use the
operator ??
:which is, IMHO, more readable.
As for your question, I can't see where's the point in using Null Object pattern for value type, as you already noted they can't hold a null value unless they are declared as Nullable so you will always have a valid value (valid in the language domain but maybe not valid in the application domain). So, this is a whole different question.
What you have to do with a null pointer really depends on the context, maybe a Null Object is suitable, but if it's not feasibile you should throw an exception or maybe use some default...