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

2

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?

Erkan answered 6/5, 2018 at 14:29 Comment(0)
F
10

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.

Fernanda answered 6/5, 2018 at 23:31 Comment(0)
C
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

Chasechaser answered 6/5, 2018 at 23:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.