解析用户内容到存储库.哪种方法更好?
本文关键字:方法 更好 存储 用户 | 更新日期: 2023-09-27 18:01:33
在阅读了许多不同的设计模式后,我对我目前的项目有一个问题,我希望有人能帮助我。
我的项目将不同的用户文件作为输入,并将它们转换为易于使用的对象存储库。
例如:Userfile A with the content:
"id:a" - "value1:contentA1" - "value2:contentB1"
"id:b" - "value1:contentA2" - "value2:contentB2"
"id:c" - "value1:contentA3" - "value2:contentB3"
现在我看到了两种不同的方法来解析这个文件为对象(哪个更好?):
1)
我们有一个实体类:
public class UserContent
{
public int ID { get; set; }
public string Value1 { get; set; }
public string Value2 { get; set; }
}
获取用户文件中的一行并将其解析为对象的服务:
public class UserContentParser
{
public UserContent ParseUserContent(string content)
{
// ...
// splitting the content
// ...
return new UserContent
{
ID = id,
Value1 = value1,
Value2 = value2
};
}
}
ParseController:
public class ParseController
{
private Repository _repository = new Repository();
private UserContentParser _userContentParser = new UserContentParser();
public Repository StartParsing(File userFile)
{
// ...
// reading file
// ...
foreach(var contentLine in userFileContent)
{
_repository.AddUserContent(_userContentParser.ParseUserContent(contentLine));
}
}
}
我看到的另一种方法如下:
2) 这个方法只包含两个类(没有服务类):
public class UserContent
{
public UserContent(string content)
{
// ...
// splitting the content
// ...
ID = id;
Value1 = value1;
Value2 = value2;
}
public int ID { get; set; }
public string Value1 { get; set; }
public string Value2 { get; set; }
}
public class ParseController
{
private Repository _repository = new Repository();
private UserContentParser _userContentParser = new UserContentParser();
public Repository StartParsing(File userFile)
{
// ...
// reading file
// ...
foreach(var contentLine in userFileContent)
{
_repository.NewUserContent(contentLine);
// in this method the repository creates the
// new UserContent(contentLine)
}
}
}
项目还包含一些插件,这些插件获取到存储库的引用,以便与包含的对象一起工作。
这里哪种方法更好?有没有更好的选择?如果需要其他依赖项来解析用户内容,会发生什么?如果实体依赖于服务,或者在实体对象中没有依赖关系更好吗?还有一个问题,UserContent类是DTO吗,因为它是用来解析用户内容并传递给其他插件的?
我希望有人能帮助我解决我的许多问题。
问候,Gerrit
你确实有很多问题很难回答,因为它们很大程度上取决于你的背景,这是对你的暗示,而不是对我们的。此外,我认为你在事前担心得太多了,在不该考虑的时候想得太多了。
然而,作为一般建议,您应该遵循SRP并将每个职责放在自己的类中,因此将解析器作为单独的类是有意义的。把它放在一个单独的类中,将允许你从中提取一个解析器接口,并有多个实现和管理解析器的依赖关系,如果你曾经得到过。
你应该担心"如果"的问题出现在你身上,或者当你知道他们会根据以前的经验来找你,而不是以前。