开发者

Avoiding dependency carrying

开发者 https://www.devze.com 2023-01-01 15:41 出处:网络
When coding, I开发者_Go百科 often come across the following pattern: -A method calls another method (Fine), but the method being called/callee takes parameters, so in the wrapping method, I pass in p

When coding, I开发者_Go百科 often come across the following pattern:

-A method calls another method (Fine), but the method being called/callee takes parameters, so in the wrapping method, I pass in parameters. Problem is, this dependency carrying can go on and on. How could I avoid this (any sample code appreciated)?

Thanks


Passing a parameter along just because a lower-layer component needs it is a sign of a Leaky Abstraction. It can often be more effective to refactor dependencies to aggregate services and hide each dependency behind an interface.

Cross-cutting concerns (which are often the most common reason to pass along parameters) are best addressed by Decorators.

If you use a DI Container with interception capabilities, you can take advantage of those to implement Decorators very efficiently (some people refer to this as a container's AOP capabilities).


You can use a dependency injection framework. One such is Guice: see http://code.google.com/p/google-guice/


Step 1: Instead of passing everything as separate arguments, group the arguments into a class, let's say X.

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

Step 3: Create an interface class of which class X inherits. Put all the getters in the interface (in C++ this is as pure virtual methods).

Step 4: Make the called methods only depend on the interface.


Refactoring: Introduce Parameter Object

You have a group of parameters that naturally go together?

Replace them with an object.

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

The advantage of the parameter object is that the calls passing them around don't need to change if you add/remove parameters.

(given the context of your answers, I don't think that an IoC library or dependency injection patterns are really what you're after)


Since they cannot be (easily) unit tested, most developers choose to inject objects into Views. Since the views are not (normally) used to construct other views, that is where your DI chain ends. You may have the issue (which I have run into every once in ahwile) where you need to construct objects in the correct order especially when using a DI framework like Unity where an attemt to resolve the object will deadlock. The main thing you need to worry about is circular dependency. In order to do this, read the following article:

Can dependency injection prevent a circular dependency?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号