我们什么时候应该考虑使用私有的还是受保护的?
只是想知道,我们什么时候应该对模型中的某些方法真正必须使用 private
或 protected
?
有时我不厌其烦地将我的方法分组为 private
或 protected
。我就让它保持原样。但我知道这一定是一个不好的做法,否则这两个分组将不会在编程中创建。
谢谢。
Just wondering, when should we actually must use private
or protected
for some methods in the model?
Sometimes I can't not be bothered to group my methods in private
nor protected
. I just leave it as it is. But I know it must be a bad practice, otherwise these 2 groupings won't be created in programming.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
record.method()
,则“public”self.method()
,则“private” "self.method() # in subclass
,那么“protected”record.method()
, then "public"self.method()
, then "private"self.method() # in subclass
, then "protected"我会给出我的意见,也许我会因此而受到批评,但我不关心 Ruby 中的 protected 或 private。事实是,Ruby 像对待成年人一样对待你,如果你想从类外部运行私有方法,你可以(有 是 方法)。您可以在类外部运行受保护的方法。您甚至可以重新分配常量...基本上您可以做任何您喜欢的事情。
这就是我喜欢它的原因,这是你的责任。我的感觉是,要将某些内容标记为受保护或私有,您需要做两件事:
此外,您还使测试变得更加困难,因为测试私有方法可能是一个真正的痛苦(请参阅在 Ruby 中对受保护和私有方法进行单元测试的最佳方法是什么? 解决方法)
出于最后两个原因,我不'别理他们。如果您确实希望在类/方法和消费者(无论是代码还是开发人员)之间建立某种屏障,那么还有其他更有效的方法(代理、混淆、加密、密码保护方法等)。否则,为什么不让他们访问您使用过的相同工具呢?
I'll give my opinion, and maybe I'll get a kicking for it, but I don't bother with protected or private in Ruby. The reality is, Ruby treats you like an adult, if you want to run a private method from outside the class, you can (there are ways). You can run protected methods outside the class. You can even reassign constants... you can do whatever you like, basically.
And that's why I like it, it's your responsibility. My feeling is, that to mark something as protected or private you are doing two things:
and in addition, you're making it harder to test, as it can be a real pain testing private methods (see What's the best way to unit test protected & private methods in Ruby? for ways around it)
For those last two reasons, I don't bother with them. If you really wanted some kind of barrier between your classes/methods and the consumers (be they code or developers) then there are other, more effective ways (proxies, obfuscation, encryption, password protected methods etc). Otherwise, why not give them access to the same tools you used?
我不知道 Ruby 是一个特殊情况,但我认为答案也与其他语言相同,所以这里是:
私有方法只能由同一类的成员访问,而受保护的方法也是适用于扩展声明该方法的基类的类的成员。
I don't know Ruby as a special case, but I assume the answer would be the same as for other languages too, so here it is:
A private method can only be accessed by members of the same class, whereas a protected is also available for member of classes that extend the base class where the method is declared.