Exposing Member Variables with ButterKnife

僤鯓⒐⒋嵵緔 提交于 2019-12-11 00:32:11

问题


Curious question, I'm using ButterKnife and I just discovered you can't use in private methods because ButterKnife creates classes that use them. Doesn't that violates the principle of encapsulation? I mean, then your variables will be exposed to other classes as well, no?


回答1:


You are totally right, using Butterknife violates the principle of encapsulation.


Butterknife uses its own generated code to perform view look-ups. And those look-ups are done in separate class(-es) hence the fields cannot be private.

Quote:

The generated code exists in a class outside of this class, thus the fields are truly being accessed outside of the class, hence not private. If you see other generated code that is accessing private fields, it is using reflection to by-pass the private access restriction, which means you have fields that look private but are actually being accessed outside of the class.

Using reflection would not only be the same thing under the hood but also significantly slower compared to view look-ups.


Anyway, those classes that use Butterknife to perform view binding should not be initialized anywhere apart of classes that are responsible for the same thing (view binding, that is) so violating encapsulation is not a big deal. For example: Activities can have instances of Fragments, Fragments/Activities can have instances of RecyclerViewAdapters because all of these are responsible for view binding, but ViewModel (MVVM architecture) for example should not have an instance of Fragment/Activity or any View in general because it has nothing to do with view binding.

Good luck. :)



来源:https://stackoverflow.com/questions/50901495/exposing-member-variables-with-butterknife

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