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 likeList<Car>
in this case) grouped into theCar
class.
Is there a best practice that covers this?
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 ;-)
Neither.
Have an interface called
ICarOwner
that is implemented byEmployee
andCompany
(or their derivations), then create the classCarOwnership
with attributesCar
(of typeCar
orICar
) andOwner
(of typeICarOwner
).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.