告诉不要问并在任务之间共享状态
在这个简单的例子中(当然,我的现实世界问题有点复杂,尽管基础知识是相同的),我如何强制告诉不要询问最大?我想最大限度地告诉不要在过程方法中询问,在当前状态下,它更难模拟和测试。
public class Processor
{
public void Process()
{
var data = new Task1().DoStuff();
new Task2().DoStuffToData(data);
}
}
public class Task1
{
public Data DoStuff(){return new Data();}
}
public class Data {}
public class Task2
{
public void DoStuffToData(Data data){}
}
编辑:更新了更多 DIish 示例
public class Processor
{
public Processor(ITask1 task1, ITask2 task) {...}
public void Process()
{
var data = task1.DoStuff();
task2.DoStuffToData(data);
}
}
In this simple example (ofcourse my real world problem is a tad more complex, although the basics are the same), how do I enforce tell dont ask to the max? Id like to maximize tell dont ask in the process method, in its current state its harder to mock and test.
public class Processor
{
public void Process()
{
var data = new Task1().DoStuff();
new Task2().DoStuffToData(data);
}
}
public class Task1
{
public Data DoStuff(){return new Data();}
}
public class Data {}
public class Task2
{
public void DoStuffToData(Data data){}
}
EDIT: Updated sample more DIish
public class Processor
{
public Processor(ITask1 task1, ITask2 task) {...}
public void Process()
{
var data = task1.DoStuff();
task2.DoStuffToData(data);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
从 tell-dont-ask 的角度来看,这段代码似乎并不算太糟糕。
告诉-不要-询问基本上意味着您不应该查询对象的状态,根据其状态做出决定,然后告诉同一个对象做什么。如果对象拥有它需要的所有信息,它应该自行决定。
您从
task1
获取数据,并通过task2
使用此信息,而无需告诉task1
要做什么。所以我认为从“告诉而不是询问”的角度来看,这是可以的。关于 Processor.Process:也没有任何问题。客户端将调用
myProcessor.Process
,从而告诉它要做什么,而不需要询问。告诉-不要-询问看起来不错,也许代码中还有其他你不喜欢的地方?
例如,您可以考虑将
DoStuffToData
放入Data
类中,从而将状态和行为结合起来。但这是否更好取决于模型及其上下文。This code doesn't seem too bad from a tell-don't-ask perspective.
Tell-don't-ask basically means you shouldn't query an object about it state, make a decision based on it's state and then tell the same object what to to. If the object has all the information it needs, it should decide for itself.
You get data from
task1
and consume this information withtask2
, without tellingtask1
what to do. So I'd say this OK from tell-don't-ask perspective.With regard to
Processor.Process
: nothing wrong there either. A client would callmyProcessor.Process
and thereby tells it what to do, without asking.Tell-don't-ask looks OK, maybe there is something else about the code you don't like?
For instance, you could consider putting the
DoStuffToData
in theData
class, thereby combining state and behavior. But whether this is better depends on the model and its context.一种选择是使用依赖注入 (DI)。但是,请确保这不会使您的代码过于复杂。 DI 对于单元测试和模拟很有用,但它也可以导致类那些太小了。
One option is to use Depenancy Injection (DI). However, ensure that this does not over-complicate your code. DI can be useful for unit testing and mocking, but it can also lead to classes that are too small.