1

I'm trying to follow the SOLID concepts and at same time be DRY (not to repeat myself).

I have a parent class that is sharing a method between its subclasses, but this method is not used in the parent class itself:

class ParentClass
  def locals
    { id: ..., result: ... }
  end
  ...
  private

  def method_used_in_descendants  # this method is not used in ParentClass
  end
end

class ChildClass < ParentClass
  def locals
    super.merge { whatever: method_used_in_descendants, one_result: ... }
  end
  ...
end

class AnotherChildClass < ParentClass
  def locals
    super.merge { whatever: method_used_in_descendants, another_result: ... }
  end
  ...
end

# And not all the descendants of ParentClass need method_used_in_descendants:
class AnotherChildClass < ParentClass
  def locals
    super.merge { whatever: my_private_method }
  end
  ...
end

Is this method method_used_in_descendants created in the ParentClass a bad practice?

Thanks

Albert Català
  • 2,026
  • 2
  • 29
  • 35
  • 7
    _"a parent class that is sharing a method between its subclasses"_ – inheritance is for specialization, not for sharing code. Consider moving the shared method into a module that is included by the subclasses (if needed). – Stefan Jun 04 '21 at 10:09
  • True! something smelled me there – Albert Català Jun 04 '21 at 11:14
  • Seems fine, like an abstract method. You can just use a mixin, as already said. Also, because of duck typing, don't need inheritance or a mixin, and can just use `my_class.respond_to?(:my_method)`, but of course this requires an if-statement that you might not want. If there are a whole bunch of methods, then better to use a mixin or a parent class like you're doing and just do `my_class.is_a?(ParentClass)` check. Different ways. Hard to tell with this simple example, but for this simple example, most Ruby code just uses duck typing and doesn't worry about it. – esotericpig Jun 07 '21 at 09:52

0 Answers0