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?
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With