我有这个类,它创建一个文档并保存它:
public class DocCreator
{
private IDocumentStore _documentStore;
public DocCreator(IDocumentStore documentStore)
{
_documentStore = documentStore;
}
public void CreateAndSave()
{
var doc = new Document();
doc.Title = "this is a title";
doc.Content = whateverStream;
doc.Hash = CalculateHash(doc.Content);
//[do more things to create a doc]
_documentStore.PersistToDisk(doc);
}
}
我觉得它很不错,因为保存内容的代码隐藏在DocumentStore
中。但我们可以更进一步,将调用_documentStore.PersistToDisk(doc);
移到另一个类,如下所示:
public class DocCreatorWorkflow
{
private IDocumentStore _documentStore;
public DocCreatorWorkflow(IDocumentStore documentStore)
{
_documentStore = documentStore;
}
public void CreateAndSave()
{
var docCreator = new DocCreator();
var doc = docCreator.Create();
_documentStore.PersistToDisk(doc);
}
}
在上面的示例中,我创建了另一个类,它调用了两个lower
类,因此负责“工作流程”。它可能更清洁,但它也使事情更复杂。不是吗?
或者我应该总是选择第二种选择吗?
答案 0 :(得分:0)
我会使用选项2.您需要修改DocCreatorClass,因为它不再负责将其保存到磁盘:
public static class DocCreatorClass
{
public static Document Create()
{
Document doc = new Document();
// Property assignment code here.
return doc;
}
}
它将是静态的,因此您不需要实例化DocCreatorClass。我还将在DocCreatorWorkflow类中为Create和Save创建单独的函数:
public class DocCreatorWorkflow
{
public IDocumentStore _documentStore;
public DocCreateWorkflow(IDocumentStore documentStore)
{
}
public void Document Create()
{
return DocCreatorClass.Create();
}
public void Save(Document doc)
{
_documentStore.PersistToDisk(doc);
}
public void CreateAndSave()
{
Save(Create());
}
}
这样,您不必总是立即将新创建的文档保存到磁盘。 CreateAndSave()将是一个方便函数,在其中调用Save()和Create(),以防您的程序想要立即保存新文档。
这种类型的设计绝对是更复杂的编码。从长远来看,它更容易查看和维护,因为每个函数只做一件事。
我个人坚持(大部分时间,因为可能有例外)一类,一个责任规则。这使您在发现功能不起作用时更容易找到项目的一部分。当您修复它时,您可以放心,应用程序的其余部分(其他任务,即类)不受影响。对于函数,我喜欢以这样的方式创建它们:在类中,不会在两个或更多不同的地方重复代码块。这样,您就不必追捕所有相同的代码块来进行更新。
答案 1 :(得分:0)
根据可用信息,选项二看起来更好(尽管可能有其他信息可能会改变这种判断)。
但是,一般来说,你如何确定哪一个更好?我认为,最好首先将问题概念化,而不涉及代码。例如,在这种情况下,在我看来,有三个问题。 1)创建文档2)持久化文档3)执行涉及创建和保存文档的逻辑(某个工作单元)。关键是,第三个问题与前两个问题是分开的。 DocCreator和DocumentStore都不知道他们是以这种方式被调用,或者是其他方式。因此,这不是他们的关注。