Search code examples
classmodulecrystal-lang

When to use a class vs. module extending self in Crystal?


In Crystal, there's two different ways to achieve similar results:

Creating a class...

class Service
  def self.get
    # ...
  end
end

or a module extending self:

module Service
  extend self

  def get
    # ...
  end
end

Both can invoke the method get by Service.get.

But when to use a class or a module? What's the difference between Crystal's classes and modules?


Solution

  • There is not much difference between class and module regarding definition of class methods. They are however fundamentally different in the fact that a class defines a type that can be instantiated (Service.new). Modules can have instance methods as well, but they can't be instantiated directly, only included in a class.

    If you only need a namespace for class methods, you should use module. class would work fine for this too, but conveys a different meaning.

    Btw: While you can't extend or include a class, in a module you can write def self.get instead of extend.