如何从NilClass继承或如何模拟类似功能 [英] How to inherit from NilClass or how to simulate similar function
问题描述
我只想使用Null对象设计模式,但是我发现我可以继承NilClass.
I just want to use Null Object Design Pattern, but I found I can inherit from NilClass.
我可以写一个没有?"的方法.并返回false,但是如果用户在下面编写代码怎么办
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
为澄清我想做的是:
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.下面是一个示例:
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:
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
输出:
obj is nil
Hello from null land
只记得使用#.nil吗?用于所有要求Null和Nil为假色的支票.
Just remember to use #.nil? for any checks that require Null and Nil to be false-ish.
CustomNil = Class.new(NilClass)
class CustomNil
def self.new
###!!! This returns regular nil, not anything special.
end
end
[为简洁起见,删除了测试]
[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继承或如何模拟类似功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!