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
}
}
Related
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.
I am trying to apply the State Design Pattern to an instant messenger program that I am building. The program is built on top of an existing instant messenger API. I am essentially creating a wrapper class to simplify the process of sending a message. (The wrapper class is going to be used by several automated scripts to fire off messages when some event occurs.)
Here is what I have so far:
A Messenger class that will serve as the client interface and hold a reference to the current state.
An AbstractMessengerState class from which all of the concrete states will inherit.
Several concrete State classes representing the various states (e.g. SessionStarted, LoggedIn, LoggedOut, etc.)
The problem I am having is where to store the state data. That is, which class(es) should store the fields that I need to carry out the business logic of the messenger program. For example, I have a Map data structure that maps userIDs (strings) to the objects used by the underlying API. I have a Session object that is used to access various messenging components and to log in and out of the messenger server. These objects need to be shared between all the subclasses.
If I store this data in the base class than I will be duplicating data every time I instantiate a new State. Is there a way to ensure that the data in the base class is accessible by the subclasses without duplicating the fields?
UPDATED
Ok, after reading a related post I am going to try to store everything in the Context (Messenger) class and see how that goes.
I'm writing a database manager layer of a web service.
I have to decide ho to implement my library: this is the situation.
I have a class, PersistenceUnit:
private static RazoooCore rc;
private static DBInstance db;
protected ODatabaseDocumentTx getDb(){return db;}
protected RazoooCooore getRc(){return rc;}
public static void startPersistence (){
//here I get an instance of rc and db
}
that start my db service and allow me to connect to it. What I want is to write class that implement persistence method, like addUser(...), or deleteFile(...) and so on.
My doubt is how to realize these method. Because I have two big classes of operations (one on users and the other on files) I thought to create to class (User and File) and to implement public static method on them, or, and is the same, create two singleton.then the application layer will have to call method without having to create and destroy object each time.
Is this a good way to realize my layer? Is, in this way, well handled concurrency, or is there a better way (perhaps a pattern) to maximize performance and multithreading?
Certainly this is not a memory-bound layer, because upper layer doesn't have to continuously
create object.
Thank you
There were lots of discussions about if an object should (or not) be responsible of persist itself, this is, should an User class have a Save method? Well, it depends. However, currently we hardly ever see that pattern.
I think the persistence logic has to be in a data access layer, probably in repositories (UserRepository and FileRepository). And this has nothing to do with neither performance nor multithreading because both issues (performance and concurrency) are in the database.
That´s my opinion.
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).
In my java program, I had a book class and a library class.
The library stores the book object in an array list and then I display it on the screen.
I can add the book and remove the books using functions.
I also use AbstractJtableModel for adding and removing the books.
But now I want to use a database, MySQL, instead of an array list.
How should I change my program?
well, you need to write the whole application :)
you need to create a db, with at least one table, you need to add mysql jdbc library to classpath and using jdbc you can insert/select/update/delete data from DB.
Alternatively, you need to add jdbc and use ORM framework like Hibernate, but depending on your Java knowledge this way can be harder (but easier to maintain in future, if you create big application). Here you can download simple hibernate application, which does CRUD operations with Honey :), you can extract interface similar to suggested by Javid Jamae from TestExample class, and exchange Honey class with Book according to your needs
You might consider using the Data Access Object (DAO) pattern. Just do a Google search and you'll find tons of articles on the topic. Essentially, you'll create a LibraryDao interface with methods like:
public interface LibraryDao {
public void storeLibrary(Library library)
public Library loadLibrary(long id)
public List<Library> searchByTitle(String title)
//...
}
You can implement this interface with straight SQL, or you can use an Object Relational Mapping (ORM) tool to implement it. I highly recommend reading up on Hibernate and the JPA specification.
Abstract the retrieval and storage of the books into a class by itself - you don't want that persistence logic intermingled with your business logic. I'd suggest creating an interface called something like "BookStorageDAO" and then you can have various implementations of that interface. One implementation may be to store the books in an ArrayList while another may be to store the books in a Database.
In this way, you can utilize the interface in your business logic and swap out the implementation at any time.
You would still use the ArrayList in your GUI to persist and display the data. The difference would be you need logic to save and load that ArrayList from a database so that the data is stored even after the program ends.
Side note, extends DefaultTableModel as opposed to AbstractJtabelModel. It completes some of the methods for you.
You don't need a DAO per se, but those answers aren't wrong.
Separation of Concern
What you need to do is separate your application based on concern, which is a pattern called separation of concern. It's a leak to have concerns overlap, so to combat this, you would separate your application into layers, or a stack, based on concern. A typical stack might be include:
Data Access Layer (read/write data)
Service Layer (isolated business logic)
Controller (Link between view and model)
Presentation (UI)
etc., but this will only partly solve your problem.
Program To The Interface
You also (as the others have mentioned) need to abstract your code, which will allow you to make use of dependency injection. This is extremely easy to implement. All you have to do is program to the interface:
public interface PersonService {
public List<Person> getAllPersons();
public Person getById(String uuid);
}
So your application would look like this:
public class PersonApp {
private final PersonService personService;
public PersonApp(PersonService personService) {
this.personService = personService;
}
}
Why is this better?
You have defined the contract for interacting with the Person model in the interface, and your application adheres to this contract without having any exposure to the implementation details. This means that you can implement the PersonService using Hibernate, then later decide you want to use JPA, or maybe you use straight JDBC, or Spring, etc. etc., and even though you have to refactor the implementation code, your application code stays the same. All you have to do is put the new implementation on the classpath and locate it (tip: the Service Locator pattern would work well for that).