过程编程的依赖注入 [英] Dependency Injection for Procedural Programming

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

问题描述

假设我决定用C或任何其他过程编程语言编写一个大型应用程序.它具有如下所示的具有呼叫依赖关系的功能:

Suppose I've decided to write a large application in C, or any other procedural programming language. It has functions with call-dependencies that look like this:

A
|
+-------------+
|             |
B1            B2
|             |
+------+      +------+
|      |      |      |
C11    C12    C21    C22

显然,对叶子函数C11,C12,C21和C22进行单元测试非常容易:设置输入,调用函数,声明输出.

Obviously, unit-testing the leaves functions, C11, C12, C21, and C22 is very easy: Setup the inputs, invoke the functions, assert the outputs.

但是对B1,B2和A进行良好的单元测试的正确策略是什么?

But what is the proper strategy to enable good unit-testing for B1, B2 and A?

依赖注入建议将B1(也称为B2)声明为跟着吗?

Would Dependency Injection suggest that B1 (and B2 also) be declared as followed?

// Declare B1 with dependency injection for invoking C11 and C12.
int B1(int input, int (*c11)(int), int(*c12)(int));

但是,如果我有很多次通话,该策略似乎就无法扩展.试想一下A的声明是什么样的:

But that strategy does not seem scalable if I have many layers of calls. Just imagine what the declaration for A would look like:

int A(int input, int (*b1)(int, int (*)(int), int(*)(int)), 
                 int(*b2)(int, int (*)(int), int(*)(int)),
                 int (*c11)(int),
                 int (*c12)(int),
                 int (*c21)(int),
                 int (*c22)(int));

好!必须有更好的方法.

Yuck! There has to be a better way.

有时候,我觉得DI和其他旨在促进模块化和易于维护的类似模式实际上会妨碍代码的清晰度,并使应该直接编码成无意义的抽象和复杂的间接寻址的事情变得复杂.

Sometimes, I feel that DI and other similar patterns that purport to promote modularity and ease of maintenance actually hampers code clarity and complicates what should be straightforward coding into nonsense abstractions and convoluted indirections.

Perl和Ruby等C语言大型软件项目如何处理单元测试?

How do large software projects in C, like Perl and Ruby, deals with unit-testing?

推荐答案

如果只需要DI进行单元测试,则可以使用链接器来完成.

If you only require the DI for unit testing you may use the linker to do it.

我的意思是功能B1& B2在标头中声明,并由函数A使用,因此B函数的实现由链接器提供.您只需要为单元测试提供一个不同的C文件.这应该不是什么大问题,因为无论如何您可能都有用于单元测试的自己的makefile.

What I mean is that the functions B1 & B2 are declared in a header and used by function A, so the implementation of the B functions is provided by the linker. You just need to provide a different C-File for unit tests. This should not be a big problem, as you probably have your own makefile for the unit test anyhow.

如果在运行时需要动态依赖项解析,则应为函数指针使用工厂模式(函数返回函数指针),并在需要时将其从工厂中拉出.工厂可以根据全局情况决定要返回什么函数.

If you require dynamic dependency resolution at runtime you should use a factory pattern (a function returning the function-pointer) for function pointers and pull them from the factory when required. The factory may decide depending on global context what function to return.

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

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