Search code examples
androidannotationsbutterknife

Exposing Member Variables with ButterKnife


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?


Solution

  • 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. :)