user1161818 user1161818 - 2 years ago 84
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

class Bar
attr_accessor :val_one, :val_two
include Fooable

I found arguments for and against whether it's a good practice. The obvious alternative is passing
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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download