这是一个简单风格的问题。在 Ruby 代码中声明访问控制的首选方法是什么?
示例A:
#!/usr/bin/env ruby
class MyClass
def method1 # this is public by default
#...
end
protected # subsequent methods will be protected
def method2
#...
end
private # subsequent methods will be private
def method3
#...
end
public # subsequent methods will be public
def method4
#...
end
end
或示例 B:
#!/usr/bin/env ruby
class MyClass
def method1
#...
end
def method2
#...
end
def method3
#...
end
def method4
#...
end
public :method1, :method4
protected :method2
private :method3
end
从语法上讲,我喜欢示例 B。A 在 protected
/private
方法之后声明的 public
方法之间引入了歧义,尽管我看不出原因您不应在将 method1
指定为 public
后才调用它。
但这不是我喜欢的。行业定义的标准是什么?
最佳答案
我唯一见过第二种方法是在 Ruby 书籍中,并且只是作为“你也可以这样做”的示例。
并且您很少看到像第一种方法那样使用“public”,因为它是默认设置,人们只是在任何 protected /私有(private)声明之前定义所有公共(public)方法。
关于ruby - 声明访问控制的首选 Ruby-ist 方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3751024/