开发者

Single Responsibility Principle - Loading a list from a file?

开发者 https://www.devze.com 2023-03-22 03:47 出处:网络
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:

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 t开发者_高级运维he 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.


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.


You probably should not have a CarLoader class. At least based on what you've shown, your CarService class doesn't look very useful either. At least right off, it looks like (if it does anything useful at all) your CarService is basically trying to build a set on top of a List. I think I'd write the code something like this:

class Car { 
// ...
    friend std::istream &operator>>(std::istream &is, std::Car &c) { 
        return is >> c.model >> c.year >> c.color;
    }
    friend std::ostream &operator<<(std::ostream &os, std::Car const &c) {
       return os << c.model << "\t" << c.year << "\t" << c.color;
};

std::set<Car> cars;

std::ifstream car_file("cars.txt");

// read data from the file:
std::copy(std::istream_iterator<Car>(car_file),
          std::istream_iterator<Car>(),
          std::inserter(cars));

std::set already knows how to add and remove items...

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号