声明访问控制的首选 Ruby-ist 方式
这是一个简单的风格问题。在 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
后调用它。
然而,这不是我喜欢的。行业定义的标准是什么?
This is a simple style question. What is the preferred means for declaring access controls in Ruby code?
Example 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
or Example 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
Syntactically, I like Example B. A introduces ambiguity between public
methods declared after protected
/private
methods, although I see no reason why you shouldn't just call method1
after specifying it as being public
.
This isn't however about what I like. What is the industry defined norm for this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我唯一见过第二种方法是在 Ruby 书籍中,并且仅作为“您也可以这样做”的示例。
而且您很少看到像第一种方法一样使用“public”,因为它是默认值,人们只是在任何受保护/私有声明之前定义所有公共方法。
The only place I've ever seen the second method used is in Ruby books, and only as a "You can also do this" example.
And you very rarely see the use of "public" like in the first method, as it's the default and people just define all their public methods before any protected/private declarations.
我认为这实际上取决于您的编码风格。如果您阅读 Bob 叔叔的“干净代码”,您(我个人)爱),我们鼓励您编写彼此紧密调用的方法或函数。在这种情况下,使用方法的可见性(如示例 B 中所示)是有意义的:
Uncle Bob 实际上为将方法紧密结合在一起提供了一个很好的案例,因为这可以防止在代码中滚动。
I think it really depends on your coding style. If you read "Clean Code" by Uncle Bob, you (which I personally loved), you're encouraged to write methods or functions that are called by each other closely together. In this case, using the visibility of a method as in example B would make sense:
Uncle Bob actually makes a good case for having methods close together, since this prevents scrolling in your code.