I know that we usually inject the dependencies by instantiating them in the constructor of the class we are injecting to. However, in my own experience, I just pass the class of the dependency as a parameter and do not instantiate in the constructor like the code below(I am currently working in Ruby):
class A
def initialize(dependency: AnotherClass)
@dependency = dependency
end
def main_operation
# do something here
@params = # do some stuff to get some params here
result = some_operation_to_perform_on_the_dependency_class
# do something with result then return
end
private
attr_reader :dependency
def some_operation_to_perform_on_the_dependency_class
denpendency.new(@params).do_some_operation
end
end
My point is it doesn't make sense to instantiate the dependency object in the constructor because I need to pass in params which I can't get at the beginning
Therefore, I would love to hear are there any better ways/practices to do this(in OOP general or specifically in Ruby)? Or this is the only way to do it?
dependency: AnotherClass
might just be a default parameter. But shouldn't it then be@dependency = dependency
? In any case, passing in a class is actually a similar process and the same overall idea, just a slightly different design - it's like passing in a factory that can create the instance for you at a later time. It's a known approach, that in other languages might manifest as say, passing in a lambda. The injected class is the factory; it's essentially an object that exists outside of your class, that you then pass in.