注入很少使用的服务 - 构造函数与方法
这个问题是关于主要基于价值对象和服务的可测试软件设计。
下面是一个简单服务的 API 示例,该服务可以将数据保存到文件中。
saveToFile(data, fileName)
saveToUniqueFile(data, fileNameGenerator)
fileNameGenerator
是一项生成随机文件名的服务。它用于查找保存数据的唯一文件名。在此示例中,fileNameGenerator
作为方法参数注入。
替代方案之一是构造函数注入,它可以简化 API:
saveToFile(data, fileName)
saveToUniqueFile(data)
保存到唯一文件当然不会每次都使用,因此似乎不需要强制构造函数参数。另一方面,服务通常通过数据进行通信,这里我们有一个服务,它确实让 API 有点混乱。
将服务作为方法参数传递是否存在任何潜在的问题/不便?在这种情况下,构造函数注入仍然是首选吗?
This question is about testable software design based on mostly value objects and services.
Here's an example of an API of a simple service that can save data to files.
saveToFile(data, fileName)
saveToUniqueFile(data, fileNameGenerator)
fileNameGenerator
is a service that generates random file names. It is used to find a unique file name to save data to. In this example fileNameGenerator
is injected as a method parameter.
One of the alternatives is constructor injection which would simplify the API:
saveToFile(data, fileName)
saveToUniqueFile(data)
Saving to a unique file certainly won't be used every time, so it would seem that a mandatory constructor parameter should not be required. On the other hand, services usually communicate via data and here we have a service and it does clutter the API a bit.
Are there any potential problems/inconveniences of passing services around as method parameters? Should constructor injection still be preferred in such situations?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将服务作为参数传递是很成问题的,因为你永远不知道什么时候需要它们。 方法及其参数构成了您的 API,而构造函数则不然。使用构造函数注入服务为您提供了更大的自由度,因为它允许您将依赖项与方法所表达的 API 解耦。
否则,您必须将方法参数传递给 API 中的所有方法,以防其中一两个方法可能需要它。
即使某项服务仅偶尔使用一次,也很少会出现问题 通过构造函数注入它们。
Passing services around as parameters is quite problematic, because you never know when you need them. Methods and their parameters constitute your API, whereas the constructor doesn't. Using the constructor to inject services gives you a much larger degree of freedom because it allows you to decouple dependencies from the API expressed by the methods.
Otherwise you'd have to pass the method argument around to all methods in your API on the off chance that one or two of them might need it.
Even when a service is only used once in a while, it's rarely an issue to use inject them via constructors.
这取决于 saveToUniqueFile() 方法“所属”的内容在您的程序上下文中是否更有意义。如果您正在使用逻辑上应该能够自我保存的对象,那么请使用构造函数注入。如果对象的保存由另一个更大的对象或服务管理,则使用方法参数 thing。
如果您使用服务作为方法参数,请确保通过引用传递它。
It depends on whether it makes more sense in the context of your program what the saveToUniqueFile() method "belongs" to. If you are working with objects that logically should be able to save themselves, then use constructor injection. If the saving of objects is managed by another, larger object or service then use the method parameter thing.
If you go with the service as a method parameter, make sure you're passing it by reference.