Where to provide entity relations: entities or services
Hi,
I have an application with a lot of entities with relations to each other. E.g cars, wheels, paint, seats, bolts, ...
The (client) application directly directly talks to a database and uses a office wide memcache, so caching is a concern as well. The object model is too large to keep everything in memory, so a form of lazy loading is needed. This is a GUI application so startup performance is an issue as well.
My question is where to draw the line between entities and their relations, are there any best practices.
Possibility one: make the entities responsible for the relations. In reality this demands that the entities keep a reference to the service
Code:
Car
.getWheels(){return carservice.getWheels(car);}
.getPaint(){return carservice.getPaint(car);}
Wheel
.getCar(){return wheelservice.getCar(wheel);}
Paint
.getCars(){return wheelservice.getCar(paint);}
Possibility two: relations are kept in the service. Entities are value objects only, keeping only a reference to the ID's of their children. Every time a child lookup is needed, the service should be called.
Code:
Car
.getID();
.getModel();
.getWheelIDs();
Wheel
.getID();
.getType();
.getCarID();
Paint
.getID();
.getColor();
.getCarID();
CarService
.getCars();
.getCar(id);
WheelService
.getWheel(id);
.getWheels(Car);
.getWheels(Car);
PaintService
.getPaints();
.getPaint(Car);
Regards,
Leen
Concerning best practices
Hmm I'd do neither nor. I would have my Entities which contain data AND relationships. The definition of a service instead should be to implement a business function or process.
So my structure would be:
Code:
public class Wheel {
...
}
public class Car {
private List<Wheel> wheels;
public void addWheel(Wheel wheel) { wheels.add(wheel); }
}
public class AssemblyService {
public void assembleWheels(...) {
// some sophisticated business logic...
Wheel w = new Wheel();
w.setSize(17);
w.setType("Snowtires");
...
Car c = getCarFromDatabase();
c.addWheel(w);
...
}
}
You should not have a dependency from the entity to the service, only the other way round. Talking best practices there should also be a DAO inbetween, which provides functionality to map your entities to the database. You might also consider to use an object-relational framework which can support you in a variety of problems, like resolving object relations (like get a car from database, fetch all assigned wheels from database, create wheel objects, create a car object and assign the wheel objects to the car object) and so forth.