Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 311
Chris Van Opstal Avatar asked Aug 12 '10 17:08

Chris Van Opstal


2 Answers

I would use the first approach in the entity classes. There should be no params to these methods as they only return all associations. The second approach which involves some simple business logic should be placed in a helper class or maybe the CarDAO, if you have one.

like image 112
tobiasbayer Avatar answered Oct 25 '22 02:10

tobiasbayer


I think there isn't a single solution. It depends how you argue. If it is the responsible of the cars to know by whom they are owned, I would used the second approach. But if it is the responsibilty of the employee to know which cars he has, then I would use the first approach.

However I personally would prefer the first approach because it seems to be easier to implemented.

like image 25
RoflcoptrException Avatar answered Oct 25 '22 01:10

RoflcoptrException