M
M
Maxim Khodyrev2017-05-04 09:50:01
Design patterns
Maxim Khodyrev, 2017-05-04 09:50:01

What is the best way to resolve class dependencies?

There is a class "A" with a method "ab" (and many others). Method "ab" generates a result using methods of several classes, including methods of class "B".
What is the correct way to resolve dependencies of method "ab" on class "B"?
What methods I see (using Laravel as an example) and their disadvantages:

  1. Injection of "B" via constructor: if the class is overgrown with dependencies, every time the class is instantiated, all dependencies will be instantiated, which I think will affect performance / memory consumption
  2. Retrieve a dependency inside a method using a service locator (in the case of Laravel, these are the resolve , app()->make methods ): when testing, you will have to spend a lot of time setting up a service container to set up dependency stubs.
  3. Wrap point 2 (obtaining a dependency through a service locator) in a separate getter method (for example, getMyService() ), and put a stub on this getter when testing: I don’t see any drawbacks yet.

What do you think?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Pavlov, 2017-05-04
@maximkou

4. Pass B as method argument ab()( function ab(B $b))
The first way is better. If the class becomes overgrown with dependencies, then you can think about refactoring. What if it doesn't overgrow?..
But no one will tell you more precisely without looking at the code - there is little data in the text of the question.
1) How often is the method called ab()? In every request? or in one of hundreds of requests?
2) is it used Belsewhere in the class A?
3) How are dependencies passed through the constructor?
new A(new B)or $b = new B; new A($b); new A($b); new A($b);or from container? After all, if it Bis already in the container, then passing it to the constructor is very simple and fast.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question