How do you access an instance variable within a mixin method? I can think of 2 ways, but both seem problematic.
-
Have the mixin method access the instance variable directly as any class method would, e.g self.text. Problem with this is that it places restrictions on where the mixin method can be used, and forces the class doing the mixing to have a particular instance method named in a particular way.
-
Pass the instance variable as a parameter to the mixin method, which would result in code like this:
example
self.do_something(self.text)
or
@thing.do_something(@thing.text)
which looks nasty to me, and doesn’t conform to the principles of object orientation.
Is there any other way to do it?, am I right to be concerned?
In general, avoid having mixins access member variables: It’s a very tight form of coupling that can make future refactoring unnecessarily difficult.
One useful strategy is for the Mixin to always access variables via accessors. So, instead of:
the mixin accesses the “text” accessor, which is defined by the including class:
What if you need to include the Mixin in this class?
Using generic and common data names in mixins can lead to conflicts when the including class uses the same name. In that case, have the mixin look for data with a less common name:
and let the including class define the appropriate accessor:
In this way, the accessor acts as sort of “impedance matcher” or “translator” between the mix-in’s data and the including class’s data.