类创建时的依赖注入也需要运行时值?

编程入门 行业动态 更新时间:2024-10-23 17:25:55
本文介绍了类创建时的依赖注入也需要运行时值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 假设您在Value对象和服务对象中划分您的系统(如面向对象的软件,由测试指导中所述)Misko Hevery调用这些newables和injectables。

当您的一个价值对象突然需要访问服务来实现它的方法时会发生什么?

假设您有一个很好的简单值对象,它是不可变的,持有一些信息,就是这样的,假设我们使用这样的东西:

CreditCard card = new CreditCard(4111-1111-1111-1111,07/10); if(card.isValid()) { // do stuff } else { //不要做东西}

到目前为止这么好。 isValid()在卡号上实现一个校验位算法,并返回true / false。

现在,我希望通过根据当前时间验证到期日期来增强系统,哟你建议这样做不会破坏Value对象/ Service对象paradim?我应该喜欢这个课程继续单元测试。

  • CreditCard 现在有一个依赖关系,但是由于创建它的方式不能被注入,所以依赖注入是不可能的。
  • CreditCard 不应该呼吁Singletons(我是全球使用Singleton的做法是不好的做法)
  • 将行为放在 CreditCardVerificationService.validateCard()意味着必须重新访问现有的所有代码。执行isValid()正在泄漏。

我知道有些事情可以做到这一点,但是什么是最干净的方式?

解决方案

我会认为它不是CreditCard对象的工作来验证任何东西。工厂将验证支票数字,以确保其正在实例化一张合格的卡,而验证服务将验证卡到期/ $限制。

Assume you divide up your systems in Value objects and Services objects (as suggested in "Growing Object-Oriented Software, Guided by Tests". Misko Hevery calls these "newables" and "injectables".

What happens when one of your value objects suddenly needs to access a service to implement it's methods?

Let's say you have a nice simple Value object. It's immutable, holds a few bits of information and that's about it. Let's say we use it something like this:

CreditCard card = new CreditCard("4111-1111-1111-1111", "07/10"); if (card.isValid()) { // do stuff } else { // don't do stuff }

So far so good. isValid() implements a check digit algorithm on the card number and returns true/false.

Now, let's say I wish to enhance the system by validating the expiry date against the current time. How would you suggest this is done without breaking the Value object/Service object paradim? I should like this class to continue to be unit testable.

  • CreditCard now has a dependency, but because of the way it is created it can not be injected, so dependency injection is out.
  • The CreditCard class should not be calling out to Singletons (I am of the position that global access to a Singleton is bad practice)
  • Putting the behaviour on CreditCardVerificationService.validateCard() means all the existing code has to be revisited. The implementation of isValid() is leaking out.

I know there are things that can be done to get around this, but what is the cleanest way?

解决方案

I would argue that it isn't a CreditCard object's job to validate anything. A factory would validate the check digits to ensure that it is instantiating a conforming card, while a verification service would validate the card for expiration/$ limit.

更多推荐

类创建时的依赖注入也需要运行时值?

本文发布于:2023-11-15 05:29:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1591565.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!