这个Ruby Style Guide告诉我们,使用self.method_name
比使用class method_name
更好。但是为什么呢?
class TestClass
# bad
class << self
def first_method
# body omitted
end
def second_method_etc
# body omitted
end
end
# good
def self.first_method
# body omitted
end
def self.second_method_etc
# body omitted
end
end
是否存在性能问题?
发布于 2012-06-10 04:04:15
class << self
擅长将所有类方法保存在同一个块中。如果方法是以def self.method
形式添加的,那么就不能保证(除了约定和如意算盘之外)不会有额外的类方法隐藏在文件中。
def self.method
擅长显式地声明一个方法是一个类方法,而使用class << self
时,您必须自己找到容器。
其中哪一个对你来说更重要是一个主观的决定,也取决于其他人有多少人在编写代码以及他们的偏好。
发布于 2015-01-10 02:09:22
如上所述,这两种风格似乎是等价的,但是使用class << self
可以将类方法标记为private
或protected
。例如:
class UsingDefSelf
def self.a; 'public class method'; end
private
def self.b; 'public class method!'; end
end
class UsingSingletonClass
class << self
def a; 'public class method'; end
private
def b; 'private class method'; end
end
end
private
仅影响实例方法。使用singleton类,我们定义了该类的实例方法,这些方法变成了包含类的类方法!
我们还可以使用def self
将类方法标记为private
class UsingDefSelf
def self.a; 'private class method'; end
def self.b; 'private class method!'; end
private_class_method :a, :b
# In Ruby 2.1 there is an alternative syntax
private_class_method def self.c; 'private class method!'; end
end
但我们不能将它们标记为protected
,因为没有protected_class_method
。(但是,由于class是其singletonclass的唯一实例,所以私有类方法和受保护类方法几乎相同,只是它们的调用语法不同。)
而且,与使用class << self
标记private
类方法相比,它不那么容易,因为您必须列出private_class_method
中的所有方法名称,或者在每个私有类方法定义中添加前缀private_class_method
。
发布于 2012-06-10 03:58:00
我假设他们认为self.*
更好,因为您可以肯定地说,它是一个类或实例方法,而不必向上滚动和搜索这个class << self
字符串。
https://stackoverflow.com/questions/10964081
复制相似问题