问题描述
假设您在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.
这篇关于类创建时的依赖注入也需要运行时值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!