首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >class vs self.method with <<:哪个更好?

class vs self.method with <<:哪个更好?
EN

Stack Overflow用户
提问于 2012-06-10 03:48:32
回答 4查看 37.3K关注 0票数 68

这个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

是否存在性能问题?

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2012-06-10 04:04:15

class << self擅长将所有类方法保存在同一个块中。如果方法是以def self.method形式添加的,那么就不能保证(除了约定和如意算盘之外)不会有额外的类方法隐藏在文件中。

def self.method擅长显式地声明一个方法是一个类方法,而使用class << self时,您必须自己找到容器。

其中哪一个对你来说更重要是一个主观的决定,也取决于其他人有多少人在编写代码以及他们的偏好。

票数 100
EN

Stack Overflow用户

发布于 2015-01-10 02:09:22

如上所述,这两种风格似乎是等价的,但是使用class << self可以将类方法标记为privateprotected。例如:

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

票数 28
EN

Stack Overflow用户

发布于 2012-06-10 03:58:00

我假设他们认为self.*更好,因为您可以肯定地说,它是一个类或实例方法,而不必向上滚动和搜索这个class << self字符串。

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10964081

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档