开发者

Using mixins vs calling a method directly

I'd like to know when is the best time to use mixins vs calling a method directly.

For example, consider HTTParty. On one of its examples https://github.com/jnunemaker/httparty/blob/master/examples/basic.rb

you can use HTTParty.get('http://twitter.com/statuses/public_timeline.json') or you can create a class that includes HTTParty and then use it as you would calling HTTParty itself.

What's the difference with me just creating something like this:

class Partay
  @base_uri = 'http://localhost:3000'
  def self.post(endpoint, options)
    HTTParty.post(@base_uri + endpoint, options)
  end
end

versus the given example:

class Partay
  include HTTParty
  base_uri 'http://localhost:3000'
end

True that in such a trivial example perhaps using the include would save more characters, but I'd imagine on a much more complicated class it doesn't really make a difference.

A few clarificatory questions: Would this be related to a composition vs aggregation argument? Is there any design or architecture best practice regarding this? Should I treat mixins as some sort of inheritance and use them as such (inheritance if it's an is-a relationship, composition if it's a has-a relationship, etc.)? Should I only mixin a module if it was inten开发者_如何学Goded to be done so (because docs say it expects certain methods from you, like Enumerable) or is it just good practice to do so? Would using a mixin mean a tighter coupling between the module and my class (and is it relatively good or bad in general)?


In the given example, there is not much difference, other than the syntax is much more friendly with the mixin, and could potentially become a DSL that you can use later.

More generally, mixins allow you to use these same functions in different classes without repeating yourself, and without extending another class (mixins are, for example, a way of working around the fact that ruby does not allow multiple inheritance). This favours reuse and goes towards the DRY philosophy dear to the ruby users. As ruby is duck-typed, mixins allows you to take full advantage of polymorphism without inheritance.

Another great advantage of mixins is that they can be added at runtime, so this means you can add behaviour to a class "dynamically".

Update: I personally prefer using modules as mixins, rather than calling methods on it as the methods then become part of your class, which means that they can access the other members of the class. I’m however reluctant to call it a is-a relationship, even though that’s what it is in practice. As the “Well-Grounded Rubyist” says, classes model entities or things (class names tend to be nouns), modules encapsulate properties or characteristics (module names tend to be adjectives).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜