user1161818 user1161818 - 7 months ago 20
Ruby Question

Should mixins make assumptions about their including class?

I found examples of a mixin that makes assumptions about what instance variables an including class has. Something like this:

module Fooable
def calculate
@val_one + @val_two
end
end

class Bar
attr_accessor :val_one, :val_two
include Fooable
end


I found arguments for and against whether it's a good practice. The obvious alternative is passing
val_one
and
val_two
as parameters, but that doesn't seem as common, and having more heavily parameterized methods could be a downside.

Is there conventional wisdom regarding a mixin's dependence on class state? What are the advantages/disadvantages of reading values from instance variables vs. passing them in as parameters? Alternatively, does the answer change if you start modifying instance variables instead of just reading them?

Answer

It is not a problem at all to assume in a module some properties about the class that includes/prepends it. That is usually done. In fact, the Enumerable module assumes that a class that includes/prepends it has a each method, and has many methods that depend on it. Likewise, the Comparable module assumes that the including/prepending class has <=>. I cannot immediately come up with an example of an instance variable, but there is not a crucial difference between methods and instance variables regarding this point; the same should be said about instance variables.

Disadvantage of passing arguments without using instance variable is that your method call will be verbose and less flexible.