Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 489
Vinicius Brasil Avatar asked May 06 '18 14:05

Vinicius Brasil


1 Answers

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.

like image 125
Johannes Müller Avatar answered Jan 08 '23 21:01

Johannes Müller