且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

穷人对遗留代码的依赖注入

更新时间:2023-02-05 22:41:24

您可能已经知道,穷人的DI有很多弊端.例如,较高级别的组件仍然依赖于较低级别的组件,而不是抽象.这使得在不引入整个代码库更改的情况下,更难替换抽象,装饰或拦截该抽象.

可怜的人的DI仍然比没有DI更好,因为至少该类别是可测试的.过去,我在遗留代码库中应用了相同的方法.我创建了一组新的类,并为它们编写了单元测试.我试图保持尽可能纯正,并且在大多数情况下能够远离穷人的DI,但我正在创造一流的学生.我无法在代码库中引入DI框架,因此我的***类使用穷人的DI并构建了完整的对象图.我的***课程是由我无法控制的其他部分实例化的,因此这对我来说是一个很好的权衡.

您认为大规模重构/去耦可行吗?

只有为要重构的类编写了一组单元测试时,才可以进行大规模重构.为了能够编写这些测试,您需要DI.而且,如果您不能引入合成词根,那么穷人的DI将是您的***选择,因为不进行测试是不可行的.将来,您也许可以更进一步,重构穷人的DI,但是直到那件事发生之前,我认为穷人的DI是您所能得到的***的.

poor man s DI seems to be an excellent way of making testable an untestable legacy codebase. Is there any drawback that i overlook? I have never seen this pattern in heavy use in refactoring legacy code. Do you think it s feasible for large scale refactoring / decoupling?

As you might already know, poor man's DI has a lot of drawbacks. For instance, the higher-level component is still dependent on the lower-level component instead of on the abstraction. This makes it harder to replace the abstraction, or decorate or intercept that abstraction without introducing sweeping changed throughout your code base.

Still, poor man's DI is still better than no DI, since at least the class is testable. I've applied the same approach in a legacy code base in the past. I created a new set of classes and wrote unit tests for them. I tried to stay as pure as possible and was able to stay away from poor man's DI in most cases, but the top classes I was creating. I couldn't introduce a DI framework in the code base, so my top classes used poor man's DI and constructed the complete object graph. My top classes where classes that where instantiated by other parts of the system I didn't control, so this was a good trade-off for me.

Do you think it s feasible for large scale refactoring / decoupling?

You can only do large scale refactoring when you wrote a set of unit tests for the classes you wish to refactor. To be able to write those tests you need DI. And if you can't introduce a composition root, poor man's DI would be your best fit, because not testing is not an option. In the future you might be able to go one step further and refactor the poor man's DI out, but till that happens, I think poor man's DI is about the best you can get.