Is overriding a modular method a good convention?

I have some kind of module template patterned

with several methods defined (default behavior) and some of them look like the method below:

def tax
  1.2
end

def do_something!
  raise "Please implement it in your class"
end

      

I read that in most cases I have to use modules over inheritance because of inheritance possibilities (inheritance alone) and when I don't need to at all super()

.

But I feel a little guilty to override all methods raise "..."

as well as some default values โ€‹โ€‹(like a method tax

), because this is a module.

What do you think?

When I need to override methods, should I use inheritance or modules?

+3


source to share


1 answer


The rule I usually follow is when a method has to be defined in a class, including a module (for example, a module acts as an interface), I always do:

def method_that_needs_to_be_defined
  raise NoMethodError
end

      

It is good practice to prevent unexpected calls to still undefined.



Example:

module Speaker
  def speak
    raise NoMethodError
  end
end

class Bird < Animal
  include Speaker

  def speak
    'chirp'
  end
end

      

+3


source







All Articles