单一职责原则 - 从文件加载列表?
假设我有一个 Car 类:
class Car
{
string GetMake()
string GetModel()
int GetYear()
}
我有一个自定义 CarService 类,其中包含汽车列表:
class CarService
{
void AddCar(Car car)
void RemoveCar(Car car)
List<Car> GetCars()
... other methods removed for clarity...
}
现在我想将汽车列表从文件加载到 CarService 类。我以前的 OOP 直觉是将其作为 CarService 类上的 LoadFromFile() 方法。然而,当我现在正在学习 SRP 和可测试性时,我不太确定。
遵循单一职责原则,正确的设计方法是什么?我应该有一个 CarLoader 类吗?
更新
我认为各种语言的解决方案应该是相同的,但我将使用 C++。如果我使用 C#、Java 或 python,我的问题将是相同的。
Say I have a Car class:
class Car
{
string GetMake()
string GetModel()
int GetYear()
}
And I have a custom CarService class that holds a list of cars:
class CarService
{
void AddCar(Car car)
void RemoveCar(Car car)
List<Car> GetCars()
... other methods removed for clarity...
}
Now I want to load a list of cars from a file to the CarService class. My old OOP instinct would be to put this as a method like LoadFromFile() on the CarService class. However as I'm learning about SRP and testability now I'm not so sure.
Following the single responsibility principle, what is the correct way to design this? Should I have a CarLoader class?
UPDATE
I think the solution should be the same in a wide variety of languages but I'll be using C++. My question would be identical if I was using C#, Java, or python.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
根据您要实现此功能的语言,我认为
load_carservice
函数或等效的静态方法就足够了。静态方法解决方案可能会违反 SRP,因为序列化格式可能会发生变化,而类的其余部分保持不变。这就是为什么我从不使用强迫我将所有内容都放在一个类中的语言进行编程的原因之一。如果您的语言强迫您这样做,并且您想严格遵守 SRP,那么将需要额外的课程。
Depending on the language you're going to implement this in, I'd say either a
load_carservice
function or an equivalent static method would suffice.The static method solution might be said to violate the SRP, because the serialization format might change while the rest of the class stays the same. This is one of the reasons why I never program in languages that force me to put everything in a class. If your language forces you to do this, and you want to adhere by SRP strictly, then an extra class would be called for.
您可能不应该拥有
CarLoader
类。至少根据您所显示的内容,您的CarService
类看起来也不是很有用。至少马上,它看起来就像(如果它做了任何有用的事情的话)您的CarService
基本上是试图在之上构建一个set
一个列表
。我想我会编写这样的代码:std::set
已经知道如何添加和删除项目...You probably should not have a
CarLoader
class. At least based on what you've shown, yourCarService
class doesn't look very useful either. At least right off, it looks like (if it does anything useful at all) yourCarService
is basically trying to build aset
on top of aList
. I think I'd write the code something like this:std::set
already knows how to add and remove items...