如何继承NilClass或者如何模拟类似的功能
我只想使用空对象设计模式,但我发现我可以从 NilClass 继承。
我可以写一个方法“nil?”并返回 false 但如果用户在下面编写代码怎么办
if null_object
puts "shouldn't be here"
end
为了澄清我尝试做的是:
record = DB.find(1)
# if it can not find record 1, the bellow code should not raise exception
record.one_attr
# and what's more
if record
puts "shouldn't be here"
end
# I don't want to override all NilClass
I just want to use Null Object Design Pattern, but I found I can inherit from NilClass.
I can write a method "nil?" and return false but what if user write code below
if null_object
puts "shouldn't be here"
end
For clarify what I try to do is:
record = DB.find(1)
# if it can not find record 1, the bellow code should not raise exception
record.one_attr
# and what's more
if record
puts "shouldn't be here"
end
# I don't want to override all NilClass
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
可能对您有用的一种方法是覆盖方法#nil?在你的 Null 对象中。
这意味着在您的代码中要测试 null 必须使用 obj.nil 吗?而不仅仅是检查 obj 是否存在。这可能是合理的,因为您可以区分 nil 和 null。下面是一个示例:
继承将起作用:
像这样使用:
输出:
记得使用 #.nil 吗?对于任何要求 Null 和 Nil 为 false 的检查。
在这一行下面是我错误的初始答案
[为简洁起见删除了测试]
使用风险自负。我还没有研究过这可能会导致什么副作用或者它是否会达到你想要的效果。但它似乎确实有一些类似 nil 的行为
An approach that may work for you is to overide the method #nil? in your Null object.
This means that in your code to test for null you have to use obj.nil? and not just check for obj existence. This is probably reasonable, since you can distinguish between nil and null. Below is an example:
Inheritance will work:
Use like so:
Output:
Just remember to use #.nil? for any checks that require Null and Nil to be false-ish.
Below this line was my WRONG initial answer
[tests deleted for brevity]
Use at your own risk. I haven't researched what side effects this may cause or whether it will do what you want. But it seems it does have some nil like behavior
我没有从
NilClass
继承,而是执行以下操作。这为您提供了已猴子修补到
NilClass
上的任何自定义方法(例如 ActiveSupport 的blank?
和无?
)。当然,您还可以添加自定义空对象行为,或更改method_missing
以不同方式处理其他调用(此方法返回 NullObject 进行链接,但您可以返回nil
例如) 。Instead of inheriting from
NilClass
I do the followingThis gives you any custom method that have been monkey patched onto
NilClass
(such as ActiveSupport'sblank?
andnil?
). You can also of course add custom null object behaviors, or changemethod_missing
to handle other calls differently (this one returns the NullObject for chaining, but you could returnnil
for example).我不认为 Ruby 实际上允许你继承 NilClass 并基于它创建一个对象:
I don't think Ruby actually allows you to inherit from NilClass and create an object based on it: