Design a Java POJO with lazy loading property - java

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.
The difference between pojos and java beans
Anemic vs. Rich Domain Models
Hopefully it helps you when you discuss wih other developers.

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.

Related

How to deal with additional methods in MVC design pattern

When we develop using MVC pattern it happens to need to having additional methods that could achieve basic operations on our models.
An example is an agregate getter that return the total count of the user records on the persistence base.
int getUsersCount();
Where is the best place to put such of those methods? In the model? In the controller?
Is there any difference between specific SDK/languages?
Java EE
Android
Laravel
vanilla PHP
...
Thanks.
I found this article that discuss about it: here it is a overview comparison between Purist OOP and Anemic Domain Model .
The overview basically explains that there are two big difference in the way you can implement a MVC design pattern.
The first way is about concetrate the methods, like the aggregate getter in this case, in a model related controller class.
For example, in Android, when we persist models in local or remote database, or we have to serialize it, or to marshall it, we tend to create those kind of ModelController classes and have so an anemic MVC pattern with clean POJO models.
class User extends MySuperModel{
int id;
String username;
//getters and setters
}
class UserController{
User getUserById(int id);
int getUsersCount();
}
The other way, consists in concentrate all the methods in the model class itself, for example as in Laravel (where controllers are demand to mainly control the post-routing and pre-rendering of a view, but doesn't tends to have other methods and neither their easy to instantiate. In this case we have a controlled domain MVC, and the additional model related methods should be in the model class itself.
class User extends Eloquent\Model{
protected $fillable = ['id', 'username']
function getUserById($id);
function getUsersCount();
}

Java adding static methods to a class

Ok guys,
Here's a question more of principle than of fact.
I have a data-structure that is used on both a client and a server.
However, on the server end, I want functionality to create the client from some sort of datastore (at the moment SQL, it used to be serialized data, but it doesn't matter).
Originally I had a giant class called something like 'Datastore' which had static methods for retrieving any stored object.
While not terrible, that's not exactly OO, and it's not exactly scalable.
So I considered moving these static methods to the datastructures themselves. However, that would mean that the shared client libraries then knew how to retrieve objects from my datastore - which is kind of silly.
So I'm now creating new classes for each object in a new datastore package, each of which holds the static methods for retrieving one object from the datastore.
My question is, how do I signify the relationship between these data manager classes and the objects that they retrieve?
Functionally, it doesn't matter. The static methods work fine. But I want to indicate to future me and other future developers that the data retriever class and the object class are tightly linked.
My first thought was to make the data retriever extend the data structure. However, that would then require declaring default constructors and implying that the class could be instantiated - which it can, but why would you?
My second thought was to then make the data retriever extend the data structure, but be abstract. That would flag the tight relationship to other developers, and also make it clear that only new methods were being added, no new fields.
However, extending a concrete class with an abstract class seems really strange, and Java still make me create default constructors.
My question is, how do I signify the relationship between these data manager classes and the objects that they retrieve?
This is a standard industry problem: how to get data from a database into an application. The common solution is to use the DAO pattern, which is to have a Data Access Object (DAO) responsible for retrieving an object from the database.
If you are retrieving an employee's personal information, salary, etc., you could have an EmployeeDAO class which would retrieve it from the appropriate table. If you are retrieving a company's profits, locations, number of employees, you could have a CompanyDAO class to retrieve this object from the database.
On top of this could be a service layer, for performing business logic; also, a DAO manager, for instantiating the DAOs and returning references to whatever classes need them.
You can still merge concepts of Repository Design Pattern and DAO Pattern, taking the application in a more concise abstraction level. The Repository acts as domain-level abstraction. Example:
public class EmployeeBO implements EmployeeRepository { // implementation of a Business Object Domain-model
#Inject
private EmployeeDAO employeeDAO; // really implementation of data access
#Override
public boolean createEmployee(String name){ // domain-oriented method
// ... some validation
employeeDAO.save(new Employee(name)); // really data access/persistence implementation
}
}

MVC with DAO/VO - Which DAO should the Controller talk to?

Background:
I have a design pattern problem that I was hoping someone may be able to solve. I program in PHP but I believe DAO/VO is popular in Java.
I have been using MVC for many years now. I designed a shopping that was MVC but used procedural programming. Thus recently I decided to develop the cart again, using OO.
Problem:
The problem I was faced with was that my Product class did not make sense to have a RetrieveAll() method.
E.g. If I had 10 products listed, from which instance would I call the RetrieveAll() method? I would have 10 choices.
Solution:
Thus, I found the DAO/VO pattern.
Unless I have not researched this pattern enough - I believe that each DB table must have a Model + DAO. No model or DAO should know about another set of models or DAO's. Thus being encapsulated.
The pattern makes perfect sense, pulling the database layer away from the Model.
However. In the shopping cart, my products are assigned categories.
A category could be electronics, clothing, etc.
There are 3 tables:
- Category (pid, name)
- Category Item (iid, name)
- Category Link (pid, iid)
From an MVC approach, it doesn't make sense of which DAO the controller should be talking to?
Should it be:
The controller talks to all 3 DAO's and then return the appropriate data structure to the View?
Or should the DAO's talk to one-another (somehow) and return a single structure back to the Controller?
Please see here for example (image)
I'm not sure what do you mean by VO. Is it value object?
I'm a huge fan of the DDD (domain driven design) approach (though I don't consider my self as guru in it). In DDD you have so called Services. Service Is an action that operates on your domain and returns data. Service encapsulates the manipulation with you Domain data.
Instead of having the controller to do all the domain logic like what items to retrieve, what DAO's to use and etc (why controller should care about the Domain anyway?), it should be encapsulated inside the Domain it self, in DDD case inside a Service.
So for example you want to retrieve all the Category items of the category "electronics".
You could write a controller that looks like this (forgive me if the code have invalid syntax, its for the sake of example):
public function showItemsByCategoryAction($categoryName) {
$categoryId = $categoryDAO->findByName($categoryName);
if(is_null($categoryId)) {
//#TODO error
}
$itemIds = $categoryLinkDAO->getItemsByCategoryId($categoryId);
if(empty($itemIds)) {
//#TODO show error to the user
}
$items = $categoryItemDAO->findManyItems($itemIds);
//#TODO parse, assign to view etc
}
This introduces at least two problems:
The controller is FSUC (Fat stupid ugly controller)
The code is not reusable. If you would like to add another presentation layer (like API for developers, mobile version of the website or etc), you would have to copy-paste the same code (expect the part of the view rendering), and eventually you will come to something that will encapsulate this code, and this is what Services are for.
With the Services layer the same controller could look like
public function showItemsByCategoryAction($categoryName) {
$service = new Item_CategoryName_Finder_Service();
$items = $service->find($categoryName);
if(empty($items)){
//#TODO show empty page result, redirect or whatever
}
$this->getView()->bind('items', $items);
}
The controller is now clean, small, and all the Domain logic is encapsulated inside a service that can be reused anywhere in the code.
Now some people believe that the controller should know nothing about DAOs and communicate with the Domain only by using Services, other says that its ok to make calls to DAOs from the controller, there are no strict rules, decide what suits better for you.
I hope this helps you!
Good luck :)
I'm not an expert in DDD either , but this is my opinion. This is the situation where the repository patern is applied. Basically, the Domain doesn't know nor care about DAO or anything else rpesistence related. At most knows about the repository inteface (which should be implemented at the infrastructure level).
The controller knows about the domain and the repository. The repository encapsulates everything db related, the application knows only about the repository itself (in fact the interface as the actual implementation should be injected). Then within the repository you have DAOs however you see fit. The repository receives and sends back only application/domain objects, nothing related to db acess implementation.
In a nutshell, anything db related is part and it's an implementation detail of the repository.
return type can be considered when deciding which dao method should go to which dao class, hence which dao should the controller talk to:
Implement one DAO class per Data Entity is more cleaner,
CRUD operations should go in to Dao classes,
C-Create, R-Read, U-Update, D-Delete
Read operations are not like Create, Update, Delete, most of the time Read operations have different flavors when considering what they return.
for Read operations, return type can be considered when deciding which dao method should go to which dao class
following are some Business Entities and there Dao
Exchange -> ExchangeDao
Company -> CompanyDao
Stock -> StockDao

Shortcut methods

My original question was quite incorrect, I have classes (not POJO), which have shortcut methods for business logic classes, to give the consumer of my API the ability to use it like:
Connector connector = new ConnectorImpl();
Entity entity = new Entity(connector);
entity.createProperty("propertyName", propertyValue);
entity.close;
Instead of:
Connector connector = new ConnectorImpl();
Entity entity = new Entity();
connector.createEntityProperty(entity, "propertyName", propertyValue);
connector.closeEntity(entity);
Is it good practice to create such shortcut methods?
Old question
At the moment I am developing a small framework and have a pretty nice separation of the business logic in different classes (connectors, authentication tokens, etc.), but one thing is still bothers me. I have methods which manipulates with POJOs, like this:
public class BuisnessLogicImpl implements BusinessLogic{
public void closeEntity(Entity entity) {
// Business Logic
}
}
And POJO entities which also have a close method:
public class Entity {
public void close(){
businessLogic.closeEntity(this);
}
}
Is it good practice to provide two ways to do the same thing? Or better, just remove all "proxy" methods from POJOs for clarity sake?
You should remove the methods from the "POJOs"... They aren't really POJO's if you encapsulate functionality like this. The reason for this comes from SOA design principles which basically says you want loose coupling between the different layers of your application.
If you are familiar with Inversion of control containers, like Google_Guice or Spring Framework-- this separation is a requirement. For instance, let's say you have a CreditCard POJO and a CreditCardProcessor service, and a DebugCreditCardProcess service that doesn't actually charge the CC money (for testing).
#Inject
private CardProcessor processor;
...
CreditCard card = new CreditCard(...params...);
processor.process(card);
In my example, I am relying on an IoC container to provide me with a CardProcessor. Whether this is the debug one, or the real one... I don't really care and neither does the CreditCard object. The one that is provided is decided by your application configuration.
If you had coupling between the processor and credit card where I could say card.process(), you would always have to pass in the processor in the card constructor. CreditCards can be used for other things besides processing however. Perhaps you just want to load a CreditCard from the database and get the expiration date... It shouldn't need a processor to do this simple operation.
You may argue: "The credit card could get the processor from a static factory". While true, singletons are widely regarded as an anti-pattern requiring keeping a global state in your application.
Keeping your business logic separate from your data model is always a good thing to do to reduce the coupling required. Loose coupling makes testing easier, and it makes your code easier to read.
I do not see your case as "two methods", because the logic of the implementation is kept in bussinessLogic. It would be akin of asking if it is a good idea java.lang.System has both a method getProperties() and a getProperty(String), more than a different method is just a shortcut to the same method.
But, in general, no, it is not good practice. Mainly because:
a) if the way to do that thing changes in the future, you need to remember that you have to touch two implementations.
b) when reading your code, other programmers will wonder if there are two methods because they are different.
Also, it does not fit very well with assigning responsabilities to a specific class for a given task, which is one of the tenets of OOP.
Of course, all absolute rules may have a special case where some considerations (mainly performance) may suggest breaking the rule. Think if you win something by doing so and document it heavily.

Java best practice library creation for flexible class creation (Factory Pattern, abstraction, and interfaces)

Imagine I am a Java software developer for a car manufacturer. I have been tasked with creating a library that will be used by numerous in-house applications. For each type of car model manufactured, I create a java object representing that model. I must be able to track not only current models, but prototype models. The prototype models will have one name that is very likely to change once it goes into production. I need to be able to use the library to account for the prototypes and flex with the name change when they are switched into production.
My question is, what is the best approach for this?
Here are my thoughts...
I have been reading several books for ideas as to best handle this situation. Immediately my mind jumps to using a factory pattern. I would have a CarModelFactory class which would return a concrete object for each model. For example:
public class CarModelFactory() {
public CarModel createCivicModel() {}
public CarModel createAccordModel() {}
public CarModel createPrototype1() {
return new ModelX();
}
public CarModel createPrototype1() {
return new ModelY();
}
Would this be the best approach? I feel like there should be another layer of abstraction. Problems I see are:
1) What if ModelX goes into production, I create a method for it and put something else in createPrototype1 method, now programs that call that method get the wrong object
2) How do I handle ModelX changing its name?
I thank you for your time!
The factory model sounds good, but I would suggest a createCarModel(String model) method, which looks up in a map the appropriate object. Then renaming a car model is a simple add/remove in that map. With appropriate synchronization, of course, to prevent a rename and a get from colliding.
The map would likely be Map<String, Class<? extends CarModel>>, and the createCar method would instantiate the class using a no-argument constructor, which you would require of all Cars.
This way, there is no recompile necessary any time you add or rename a model, as the factory class does not change its set of method signatures.
Additionally, if you override the ClassLoader, you can unload an old model and load up a new model, allowing the actual directory containing your .class files to be kept clean (no old prototype classes that have since been made into real models).

Categories

Resources