通过构造函数传递什么,通过接口传递什么? [英] What to pass via constructor and what to pass via interface?

查看:92
本文介绍了通过构造函数传递什么,通过接口传递什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是有关依赖项注入的问题。在构造服务对象时,我们在构造阶段通过构造函数传入协作者。服务对象将实现一个接口,该接口将在运行阶段被调用。

This is a question about dependency injection. When constructing a service object, we pass in collaborators via the constructor in the construction phase. The service object would implement an interface, and that would be called during the run-phase.

有时很难知道是否应通过构造函数传递特定对象还是成为服务类实现的接口的一部分?

Sometimes is is difficult to know if a particular object should be passed via the constructor or be part of the interface implemented by the service class?

是否存在选择一个选项而不是另一个选项的规则?当您知道接口只在您要编码的场景中被调用一次时,这个问题就很难解决。

Are there any rules about choosing one option over the other? The question is most difficult when you know the interface is only going to be called once in the scenario you are coding for.

推荐答案

我喜欢这样想:


  • 构造函数参数是实现细节

    • 它们适用于所有操作

    • 它们不会响应任何操作(不变)而更改

    • 没有它们就可以理解界面
    • >
    • 它们是反映应用程序接缝的配置值

    • Constructor arguments are implementation details
      • They are scoped to all operations
      • They do not change in response to any operation (invariant)
      • The interface can be understood without them
      • They are configuration values which reflect an application's seams

      • 它们的作用域是单个操作

      • 它们是运行时值,反映了应用程序的数据流

      很多技术都在正确地解决问题。例如,我们可能对自己说:我需要在用户表中创建一个新行。从这个角度来看,这些签名中的任何一个似乎都不错:

      A lot of the art is in framing the problem correctly. For example, we might say to ourselves "I need to create a new row in the user table." From that perspective, either of these signatures seems fine:

      void Insert(User user);
      
      void Insert(User user, IDbConnection dbConnection);
      

      但是,我们可以分解任务定义:

      However, we can break down our task definition:

      意图:创建新用户

      实施细节:用户是表中的一行

      让我们将任务的框架设置为我需要创建用户。这使我们可以评估上面的两个签名,而与我们的意图相匹配:

      Let's instead frame the task as "I need to create a user". This gives us a way to evaluate the two signatures above, favoring the one which matches our intent:

      void Insert(User user);
      

      对操作意图和数据适用范围的分析通常会给出可靠的结果。

      Analysis of an operation's intent and the applicable scope of its data generally gives solid results.

      这篇关于通过构造函数传递什么,通过接口传递什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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