我只想使用空对象设计模式,但我发现我可以从 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
可能对您有用的一种方法是覆盖方法#nil?在你的 Null 对象中。
这意味着在您的代码中要测试 null 必须使用 obj.nil 吗?而不仅仅是检查 obj 是否存在。这可能是合理的,因为您可以区分 nil 和 null。下面是一个例子:
class NullClass
def nil?
true
end
def null_behavior
puts "Hello from null land"
end
end
继承将起作用:
class NewClass < NullClass
end
像这样使用:
normal = Class.new
null = NewClass.new
x = [normal, null]
x.each do |obj|
if obj.nil?
puts "obj is nil"
obj.null_behavior
end
end
Output:
obj is nil
Hello from null land
只需记住使用#.nil 即可?对于任何要求 Null 和 Nil 为 false 的检查。
这条线下面是我错误的最初答案
CustomNil = Class.new(NilClass)
class CustomNil
def self.new
###!!! This returns regular nil, not anything special.
end
end
[为简洁起见删除了测试]
使用风险自负。我还没有研究过这可能会导致什么副作用,或者它是否会达到你想要的效果。但它似乎确实有一些类似 nil 的行为
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)