poor man s dependency injection for legacy code

谁说我不能喝 提交于 2019-12-11 09:47:39

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/19692806/poor-man-s-dependency-injection-for-legacy-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!