Avoiding Dependency Migration

When coding, I often come across the following pattern:

-A method calls another method (Fine), but the called / calllee method takes parameters, so in the wrap method I pass parameters. The problem is that dependency migration can go on and on. How could I avoid this (any code sample was evaluated)?

thanks

+4
source share
5 answers

Passing a parameter just because a lower layer component is required is a sign of Leaky Abstraction . It can often be more efficient for refactor dependencies to aggregate services and hide each dependency behind an interface.

Common problems (which are often the most common reason for passing parameters) are best addressed with Decorators .

If you are using a DI container with interception capabilities, you can use them to use Decorators efficiently (some call it the AOP container).

+3
source

You can use the dependency injection infrastructure. One of these is Guice: see http://code.google.com/p/google-guice/

+2
source

Step 1: instead of passing everything as separate arguments, group the arguments into a class, say, X.

Step 2: Add getters to class X to get the relevant information. The caller must use getters to retrieve information instead of relying on parameters.

Step 3: Create an interface class that inherits class X. Put all the getters in the interface (in C ++, it's like pure virtual methods).

Step 4: Make the called methods only interface dependent.

+2
source

Refactoring: introducing a parameter object

Do you have a group of options that naturally go together?

Replace them with an object.

http://www.refactoring.com/catalog/introduceParameterObject.html

The advantage of the parameter object is that calls passing them around do not need to be changed if you add / remove parameters.

(given the context of your answers, I don't think that the IoC library or dependency injection patterns is what you need)

+1
source

Since they cannot be (easily) tested, most developers prefer to inject objects into Views. Since views are not (usually) used to build other views, that is, where your DI chain ends. You may have a problem (which I ran every time in ahwile) where you need to build objects in the correct order, especially when using a DI infrastructure such as Unity, where the attemt to resolve the object will be inhibited. The main thing you need to worry about is circular dependence. To do this, read the following article:

Can injecting addiction prevent cyclic addiction?

0
source

Source: https://habr.com/ru/post/1311553/


All Articles