OOP best practice: Employee.GetCars() vs Cars.GetB

2019-04-08 01:26发布

Given the classes Company, Employee, and Car what is the preferred practice for methods to retrieve Cars associated with Company or Employee?

Employee.GetCars(params...)
Company.GetCars(params...)

Or:

Cars.GetByEmployee(params...)
Cars.GetByCompany(params...)

The first approach is the one I have generally used and always seemed the most intuitive to me. But after seeing a large code-base that used the second approach I have to admit that it's growing on me. The two things I really like about the second approach are:

  • It groups all Car related code together into one file, making the code more modular and easier to maintain.
  • There is an intuitive logic to having any method with a return value of Car (or more like List<Car> in this case) grouped into the Car class.

Is there a best practice that covers this?

8条回答
smile是对你的礼貌
2楼-- · 2019-04-08 02:25

Its all about releationships. Can one employee have more then one car? (1:N) Never reference the 1 side from the N side, thats what my teacher said. Same for the other things. If you have a 1:1, you can do both. Employee.getCar and Car.getOwner ;-)

查看更多
时光不老,我们不散
3楼-- · 2019-04-08 02:26

Neither.

Have an interface called ICarOwner that is implemented by Employee and Company (or their derivations), then create the class CarOwnership with attributes Car (of type Car or ICar) and Owner (of type ICarOwner).

When you need to need to find car ownership, you don't need to care whether the owner is an employee or a company. You just need to do CarOwnerships.GetByOwner(ICarOwner).

I hope this helps.

查看更多
登录 后发表回答