Please consider below example:
A web application creates a user object for every logged in user. This object has simple String properties for firstName, lastName ...
Each user can have a car too. Consider that fetching the user car is very expensive, so we prefer not to set the users car when user logs in. Instead we want to get car when a use case needs it.
To implement this we have created a User pojo as:
public class User() {
private String FirstName;
private String LastName;
private Car car;
//Here we have the service object, this could be injected with spring or JEE
private CarServices carServices;
public Car getCar() {
//If the car is not fetched yet, go on and get it from your service
if (car == null) {
car = carServices.getCarFromDB(...)
}
return car;
}
}
To initial user after a login:
User newUser = new User();
newUser.setFirstName("foo");
newUser.setLastName("bar");
//We just let user have service, so he can use this service latter
newUser.setCarServices( new CarServices() );
And every use case which needs the user car can get it easily:
newUser.getCar()
However, I have been argued that in this way my User object is not a simple pojo any more and this is not a good approach.
How can I achieve this requirement in better way.
解决方案
I have been argued that in this way my User object is not a simple pojo
To anwer your question I would first like to go back a bit in history.
Pojo is a plain old java object and means that you only use "standard" java. The term was created at a time when J2EE had it's hype. At this time developers coded business logic in enterprise beans and this EJBs needed a lot of infrastructure code. This fact coupled buisness logic to an implementation technology. So Rebecca Parsons, Josh MacKenzie and Martin Fowler came to the conclusion that business logic would be more reuseable and easier to test if you just use standard java. Thus they created the term pojo, because developers like fancy names.
Your User class just depends on standard java and therefore it is a pojo.
Some developers argue that a pojo should not contain any logic. These developer prefer anemic models. Others say that a rich model is the better approach. I belong to the developers who prefer a rich model over an anemic model.
If you want to remove the CarServices dependency from the User class you can implement a Car lazy loading proxy just like hibernate or a jpa implementation does.
At least here are some of my thoughts to beans, pojos, anemic and rich domain models.
Hopefully it helps you when you discuss wih other developers.