Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use a module, and when to use a class

Tags:

I am currently working through the Gregory Brown Ruby Best Practices book. Early on, he is talking about refactoring some functionality from helper methods on a related class, to some methods on module, then had the module extend self.

Hadn't seen that before, after a quick google, found out that extend self on a module lets methods defined on the module see each other, which makes sense.

Now, my question is when would you do something like this

module StyleParser   extend self    def process(text)     ...   end    def style_tag?(text)     ...   end end 

and then refer to it in tests with

@parser = Prawn::Document::Text::StyleParser 

as opposed to something like this?

class StyleParser    def self.process(text)     ...   end    def self.style_tag?(text)     ...   end end  

is it so that you can use it as a mixin? or are there other reasons I'm not seeing?

like image 204
Matt Briggs Avatar asked Apr 19 '10 23:04

Matt Briggs


1 Answers

A class should be used for functionality that will require instantiation or that needs to keep track of state. A module can be used either as a way to mix functionality into multiple classes, or as a way to provide one-off features that don't need to be instantiated or to keep track of state. A class method could also be used for the latter.

With that in mind, I think the distinction lies in whether or not you really need a class. A class method seems more appropriate when you have an existing class that needs some singleton functionality. If what you're making consists only of singleton methods, it makes more sense to implement it as a module and access it through the module directly.

like image 78
Jimmy Avatar answered Oct 01 '22 19:10

Jimmy