mixin是否应该对其包含类做出假设? [英] Should mixins make assumptions about their including class?

查看:91
本文介绍了mixin是否应该对其包含类做出假设?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现了一个mixin的示例,该示例对包含类具有哪些实例变量进行了假设.像这样:

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

我发现赞成和反对这是否是一个好习惯.显而易见的替代方法是将val_oneval_two作为参数传递,但这似乎并不常见,并且使用更多参数化方法可能会带来不利影响.

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.

关于mixin对类状态的依赖是否存在传统观念?从实例变量读取值与将其作为参数传递相比有什么优缺点?另外,如果您开始修改实例变量而不是仅仅读取它们,答案是否会改变?

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?

推荐答案

在模块中假设与包含/准备有类的类有关的某些属性根本不是问题.通常是这样.实际上,Enumerable模块假定包含/添加它的类具有each方法,并且有许多依赖于此的方法.同样,Comparable模块假定包含/前置类具有<=>.我不能立即给出一个实例变量的例子,但是就这一点而言,方法和实例变量之间并没有关键的区别.关于实例变量应该说同样的话.

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.

这篇关于mixin是否应该对其包含类做出假设?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆