When should we consider using private or protected?

痴心易碎 提交于 2020-01-01 08:43:30

问题


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.


回答1:


  • If you plan to call a method externally, record.method(), then "public"
  • If it will be used only internally, self.method(), then "private"
  • If you plan to use it internally, but also in descendants, self.method() # in subclass, then "protected"



回答2:


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:

  1. Indicating that you don't think a consumer will need it.
  2. Second guessing what someone else needs.

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?




回答3:


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.



来源:https://stackoverflow.com/questions/8730390/when-should-we-consider-using-private-or-protected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!