I have an entity domain object that has a large collection of child entity domain objects. I have to implement an operation (let's call the operation getSum) for the parent that involves filtering out most of the child objects and then summing a field in the remaining objects and returning the sum.
The database could hold hundreds of thousands of the child objects but for any single invocation of this operation, we are usually only interested in a small percentage of those child objects. Therefore, rather than loading all of the child objects into memory (in a Collection that lives in the parent) and filtering them there, I think it would be better (performance wise) to filter them on the database server. So, I have created an operation in a DAO that submits a datbase query that does this filtering and the calculate the sum.
For layering purposes, I do not want to give the client direct access to the DAO. Instead, the client will call getSum on some object and that object will then delegate to the DAO. So, my question is, WHICH object should expose getSum to the client? Should it be the parent object or some service object? For example:
Should I do this?
OR this?Code:class MyParentEntity { private MyDao dao; public void setDao(MyDao dao) { this.dao = dao; } public int getSum(FilteringParams params) { return dao.getSum(params, this); } // other operations }
In this first case, the client will call MyParentEntity.getSum(). In the second case, the client would instead call MyService.getSum(), passing an instance of MyParentEntity as a parameter.Code:class MyServiceImpl implements MyService { private MyDao dao; public void setDao(MyDao dao) { this.dao = dao; } public int getSum(FilteringParams params, MyParentEntity parentEntity) { return dao.getSum(params, parentEntity); } // other operations }
Putting the operation into MyParentEntity seems more natural because the operation involves an instance of MyParentEntity. On the other hand, it seems unnatural to give an entity object access to a DAO.
Any advice?


Reply With Quote