0

Please, help me with this basic OOP question. Here is a code example:

class A
{
    public function foo(SomeClass $someClass) {
        return $someClass->bar();
    }
}

Passing $someclass as as a function parameter is a Dependency Injection or not? And why it is so.

Consider it as an interview question. As for me, SomeClass is a dependency of class A, and it is being injected into method, so, it should be Dependency Injection. But I have not found any proofs to support my opinion.

I have checked What is dependency injection? and there are just examples of constructor and setter injection, my example is different.

user3529607
  • 160
  • 2
  • 14
  • 1
    Not sure if this is answered by https://stackoverflow.com/questions/130794/what-is-dependency-injection – Nigel Ren Jul 10 '19 at 18:17
  • @NigelRen yes, I saw it, but there are just examples of constructor and setters injections, nothing about regular methods. – user3529607 Jul 10 '19 at 18:21
  • 3
    This is also dependency injection. Most of them are found injected from constructor and setters because they are useful to multiple methods of the class. – Jumper Jul 10 '19 at 18:38
  • @yivi Thank you for the answer. Please, pay attention, that I am not setting anything in my example. I am just calling some mehtod from injection class. So it is not a setter injection. – user3529607 Jul 10 '19 at 18:41
  • 2
    Nothing about dependency injection as a concept requires an specific kind of injection. As long as you are supplying the dependency to an object, it can be said to be DI. – yivi Jul 10 '19 at 18:54

1 Answers1

2

In its most naive sense of "passing a dependency to a unit of work" then yes, it's dependency injection.

In its broader sense of "passing the dependencies necessary for a unit of work to accomplish its responsability", not really.

The goal of dependency injection is ultimately to write cleaner code, easier to reason about, maintain, test and develop. To do that, we organize responsability in a thing (be it a function, class, library or whatever). Everything that is needed for that responsability to happen should be passed in, instead of created inside of the thing, where it can't be mocked, modified, or configured.

Classes are not meant to be repositories of methods that each receive their dependencies, we can use functions for that. In this case, the "dependency" would rather be what's needed for A to know what bar() they should invoke on SomeClass.