7

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?

vinibrsl
  • 6,563
  • 4
  • 31
  • 44

2 Answers2

9

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.

Johannes Müller
  • 5,581
  • 1
  • 11
  • 25
3

But when to use a class or a module?

Use a module. In this way a module can be used as a namespace.

What's the difference between Crystal's classes and modules?

A module cannot be instantiated, and can be included inside a class

See: Modules documentation

Faustino Aguilar
  • 823
  • 6
  • 15