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?