穷人对遗留代码的依赖注入 [英] poor man s dependency injection for legacy code

查看:67
本文介绍了穷人对遗留代码的依赖注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

穷人的DI似乎是使可测成为不可测的旧代码库的一种极好的方法.我有没有忽略任何缺点?我从未见过这种模式在重构遗留代码中大量使用.您认为大规模重构/去耦可行吗?

解决方案

您可能已经知道,穷人的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.

这篇关于穷人对遗留代码的依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆