Design a Java POJO with lazy loading property

前端 未结 2 1902
悲&欢浪女
悲&欢浪女 2021-01-21 01:58

Please consider below example:

A web application creates a user object for every logged in user. This object has simple String properties for firstNam

相关标签:
2条回答
  • 2021-01-21 02:33

    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.

    • The difference between pojos and java beans
    • Anemic vs. Rich Domain Models

    Hopefully it helps you when you discuss wih other developers.

    0 讨论(0)
  • 2021-01-21 02:33

    Instead of a reference to a car, you could use a reference to a car supplier object whose implementation could cache the first result obtained (see Guava's Supplier and MemoizingSupplier classes). By doing so, you hide from the User object the fact that its car might or might not be present at instantiation time, and therefore make its implementation simpler (no more logic in the getter method).

    Another advantage of this solution would be to break the coupling between the User and the CarServices classes (no need for the carServices property anymore). One could inject a supplier whose implementation would return a reference to an already available Car object, while another could pass an implementation that forwards the call to a CarServices service.

    It wouldn't make the User class more of a POJO though (as explained in the first answer above), but people who have argued with your solution might like this one better because of it being simpler and less tightly coupled.

    0 讨论(0)
提交回复
热议问题