使用空对象模式时检查无效状态
使用空对象模式时,如何“检查”情况是否无效? 例如 当存储库中没有找到项目时,向用户显示消息“未找到”。
我必须做一个美化的空检查吗?
- if obj.equals(new NullObject()) { showNotFound(); }
- if obj.ID.equals( INVALID_ID) { showNotFound(); 这些
技术似乎违背了空对象模式本身的目的
When using Null Object pattern, how would you 'check' if a situation is invalid?
for e.g
when there's no item found in the repository, display message 'not found' to the user.
Do I have to do a glorified null check?
- if obj.equals(new NullObject()) { showNotFound(); }
- if obj.ID.equals( INVALID_ID) { showNotFound(); }
Those techniques seem to defeat the purpose of Null Object pattern itself
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
问题是您在不存在中性行为的场景中使用空对象模式。 添加到 Matthew 所说的内容中,仅当您想要调用操作而不担心引用为空时,使用此模式才有意义。
c2.com wiki 总结得很好:
The problem is you are using the Null Object pattern in a scenario where there is not neutral behaviour. Adding to what Matthew has stated, using this pattern only makes sense when you want to invoke an operation without worrying that the reference is null.
c2.com wiki sums it up nicely:
在我看来,你是对的。 如果您需要此类功能,只需使用 null,并进行 null 检查并响应您的 null 状态。
就我个人而言,我只有在“空”值有意义并且可以使用它运行时才真正发现这很有用,从而避免空检查。 如果您需要 null 值(或无效值)语义,那么 null 是有意义的(如果您忘记检查它,则会抛出异常,而不是默默地失败)。
In my opinion, you are right. If you need this sort of functionality, just use null, and do null checking and respond for your null state.
Personally, I only really find this useful where an 'empty' value makes sense and you can run with that, hence avoiding null checks. If you need null value (or invalid value) semantics, then null makes sense (and will throw exceptions if you forget to check for it, instead of silently failing).
空对象模式的目的本质上是为了避免当您想要对可能为空的值调用方法时必须执行空检查。 但由于您特别希望将空值作为特殊情况处理,因此无法绕过空值检查。
进行空检查并不一定会破坏空对象模式的目的,因为它可以帮助您避免程序中其他地方不必要的空检查。
The purpose of the Null Object pattern is essentially to avoid having to do null checks when you want to call methods on a value that is possibly null. But since you specifically want to deal with nulls as a special case, there's no way around the null check.
Having a null check doesn't necessarily defeat the purpose of the Null Object pattern, as it could help you avoid unnecessary null checks elsewhere in your program.
以这种方式使用空对象不是空对象模式,如果您确实想使用该模式,那么您可以。 例如,如果您的对象有一个 Name 属性,只需显示该属性,其中空对象将您的“未找到”消息显示为其名称......但它可能不适合您的工作方式。
Using your null object in this way isn't the Null Object Pattern, if you did want to use the pattern then you could. For example if your object had a Name property, just display that, where the null object displayed your "not found" message as its name... but it might not fit into how you're working.