Should I create new class or use the existing one - java

I have the following BO which is already there in the system
public class userBO
{
private String userId;
private String password;
private String firstName;
private String midName;
private String lastName;
private String userType;
private String userDepartment;
private String userAuthority;
//There are some more fields
//getter and setter
}
Now I want to built a dropdown in which I will display Name (firstName + lastName) and will use userId as value. So for that I will make a list of object.
So my question is should I use the existing userBO class or should I create new class something like below
public class userDropDwonBO
{
private String userId;
private String firstName;
private String lastName;
//getter and setter
}
I want to know the answer from Good Architect point of view and also performance point of view, Will there be any better performance if I user new userDropDownBO

userDropDownBO object will definitely use less memory than the above class.
It is because all your members are private intance variable, everytime a constructor is invoked, a set of all private variables will be created on stack and will be initialized to their default values so will consume more memory and initialization time.
But it solely depend on your requirement:
If other fields are required other than these three fields go for the userBO class.
If other fields are unnecessary but no of objects to be created are small in number, go for userBO.
If other fields are unnecessary but no of objects to be created are very large in number, go for userDropDownBO.
Its a personal opinion and rest is your choice.

If you are going to create a new class beside the existing one named UserBO just for the sake of binding it to the JComboBox, that will definitely be a waste of memory and waste of time as well and also you will need to provide an additional logic to map your original object of type UserBO to the the object of type UserDropDownBO.
I would say that your approach maybe applicable in case the BO itself is so complex in dealing with, so that you need to create a separate model to be used in the drop down box.

Related

Update a current object given an object of the same type

Let us suppose we have the following class:
class Credentials implements ICredentials{
String name;
String surname;
String email;
public void update(ICredentials updatedCredentials){
// do stuff here
}
}
I would like to update the fields of the current class (the strings above) , using an object of the same type, without using getters or setters. Is there a way?
PS: noob here.
You could pass the object that you want to update to a ICredentials method that updates its content : updateParam(Credentials).
Add this method in the interface and Credentials that implements it could use private fields of the parameters as an instance of a class can access to private fields without getters.
class Credentials implements ICredentials{
public void update(ICredentials updatedCredentials){
updatedCredentials.updateParam(this);
}
#Override
public void updateParam(Credentials credentialsToUpdate){
credentialsToUpdate.name= name;
credentialsToUpdate.surname = surname;
credentialsToUpdate.email= email;
}
}
But this is convoluted enough.
The real issue in your actual logic is that you want to pass ICredentials as parameter that is not necessary a Credentials. In these conditions, the interface needs to provide a way to extract the name, surname and email information.
You don't have to consider these methods strictly as getters but as methods required to fulfill the interface contract.
Without it, to extract data from the interface you should do convoluted things or downcasting from the interface to the subclass or still worse...
Assuming that updatedCredentials is the same instance of Credential, one way is that you can directly assign
public void update(ICredentials updatedCredentials){
Credentials cred = (Credentials) updatedCredentials;
this.name = cred.name;
//rest of it
}
Remember you need to declare the variable as public. But this process is very ugly. If you can use getter and setter that could be nice solution and it is the best practice

How to track before & after properties of an object?

How do we properly track changes to an object's properties in Java (specifically JavaFX)?
My application allows users to modify the properties of the underlying data model objects. When the user clicks on a "Save" button, I want to save the new state of the object to a database. However, if the user clicks on "Cancel," I need to revert back to the object's original state.
Consider the following example objects (getters omitted for clarity):
class Person {
private final StringProperty name = new SimpleStringProperty();
private final StringProperty email = new SimpleStringProperty();
private final SimpleListProperty<PhoneNumber> phoneNumbers = new SimpleListProperty<>();
public Person(String name, String email, ObservableList<PhoneNumber> phoneNumbers) {
this.name.set(name);
this.email.set(email);
this.phoneNumbers.set(phoneNumbers);
}
}
class PhoneNumber {
private final IntegerProperty areaCode = new SimpleIntegerProperty();
private final IntegerProperty prefix = new SimpleIntegerProperty();
private final IntegerProperty lineNumber = new SimpleIntegerProperty();
public PhoneNumber(int areaCode, int prefix, int lineNumber) {
this.areaCode.set(areaCode);
this.prefix.set(prefix);
this.lineNumber.set(lineNumber);
}
}
Ideally, I want the GUI to load the original Person object, and make a copy of it to bind to the UI controls (even if I need to write this method myself):
Person editedPerson = copyOf(originalPerson);
Then, if the user clicks "Cancel," do nothing. Upon clicking "Save," however, set originalPerson to be equal to editedPerson.
I have looked into cloning objects, but the general consensus seems to recommend against that as it does not ensure the original object is not changed. Also, unless doing a deep copy, any objects references within Person, for example, would not be properly copied.
The other option I've seen is to use a copy constructor but my real-world application uses much more complex objects than the sample above. There are several levels of objects nested within each object and manually copying the entire hierarchy seems like overkill.
So what is the main question? Is there already an API available (or 3rd party library) that handles this functionality? It seems to be a pretty standard expectation for a user to be able to revert their changes.

How should I populate my object?

I have an object that I want to populate with information. I retrieve the information from a number of different services. I made a helper class that has one public method and then has a number of private methods that do the work to call the services. What I have written works fine but I'm not sure if it is the correct way to do this.
You may be wondering why I need an object holding all this information. I need it all in one object because I create a json object from this java object and pass that to the javascript layer.
What is wrong with my approach and is there a programming paradigm I should be following to do something like this?
Example:
Person object with getters and setters for firstName, lastName, age, height, weight, list of favourite foods, list of favourite countries, list of comments.
Service 1 gives firstName, lastName, age, height and weight
Service 2
gives list of favourite countries and list of favourite foods
Service
3 gives a list of the comments made by the person
I have a personHelper class that looks like this:
public class PersonHelper{
public Person getPerson(userDetails){
Person person = new Person();
this.setPersonDetails(person, userDetails);
this.setFavourites(person, userDetails);
this.setComments(person, userDetails);
return person;
}
private Person setPersonalDetails(Person person, UserDetails userDetails){
returnedObj = callToService1(userDetails);
person.setFirstName(returnedObj.getFirstName());
person.setLastName(returnedObj.getLastName());
person.setAge(returnedObj.getAge());
person.setHeight(returnedObj.getHeight();
person.setWeight(returnedObj.getWeight());
return person;
}
private Person setFavourites(Person person, UserDetails userDetails){
<List>favsList = callToService2(userDetails);
person.setFavourites(returnedObj.getFavs(favsList));
return person;
}
private Person setComments(Person person, UserDetails userDetails){
<List>commentsList = callToService3(userDetails);
person.setComments(returnedObj.getComments(commentsList));
return person;
}
}
and then in my controller I call
person = personHelper.getPerson(userDetails);
jsonResponse = jsonProcessor.writeAsString(person);
return jsonResponse; // returns the ajax response to js
Thanks in advance for any help or suggestions.
EDIT: After more research I found that the object I am populating is referred to as a Data Transfer Object and I am populating it using the Java Bean method.
There's a trend these days to limit the mutability of objects so your setter-based approach, although workable, is sometimes not seen as the best way to create an object, even a data transfer type of object. One other thing to consider is how many objects know about each other and how much they know - it seems your PersonHelper class needs to know pretty much everything about UserDetails and Person. So if you add a field to Person, you need to add it to UserDetails and also add to PersonHelper to get that field populated.
For your type of object, you might find the Builder pattern useful. A builder is a short-term transient object designed to gather data for construction. Often the builder will have a fluent API, and gets passed to the (private) constructor of the transfer class. That means that all your code responsible for building the object is clear that that is its responsibility because it works with a Builder. Meanwhile, the constructed transfer object is effectively immutable and it becomes significantly easier to reason about the thread-safety of your code and to understand what values something might have at different parts.
public class Person {
private final String firstName;
private final String lastName;
private Person(final PersonBuilder builder) {
this.firstName = builder.firstName;
this.lastName = builder.lastName;
}
... usual getters etc ...
public static class PersonBuilder {
private String firstName;
private String lastName;
private PersonBuilder() {
}
public PersonBuilder withFirstName(final String name) {
this.firstName = name;
return this;
}
public PersonBuilder withLastName(final String name) {
this.lastName = name;
return this;
}
public Person build() {
return new Person(this);
}
}
public static PersonBuilder newPerson() {
return new PersonBuilder();
}
}
In this example the builder is a little over-wieldy, but when you've got twenty or thirty different pieces of data which are somehow optional it can make sense and makes for very easy to read construction code...
Person.newPerson().withFirstName("Sam").withLastName("Spade").build()
It seems to me that your 'UserDetails' object could be turned into a kind of builder. And so your 'PersonHelper' class would end up just calling userDetails.build() rather than knowing all about what fields the Person object (and userDetails object) contains.
There is no general paradigm for your question, but here are a few tips for your design:
It seems that your person data (names, favourites) is distributed among several data stores and you have to gether it all in your PersonHelper class. I don't know if this services are used anywhere else, but from the controller point of view this helper should be a service too.
Since your service invocations are independent, you can execute them in parallel
For some kind of applications it can be even better if you expose these services for UI level. For example, if data is presented in different UI blocks, client can make several asynchronous requests and display the data as soon as responses are received.

Setting different object with same attributes

This is not the first time that I've found myself in a situation in which I have to adapt two objects with almost the same data, for example:
User.java (Object returned from another library)
private String name;
private String surname;
private String email;
private String telephone;
...
getters and setters();
constructor();
MyUser.java
private String name;
private String surname;
private String email;
private String telephone;
...
getters and setters();
constructor();
I usually create a method to convert one object into another one, like this:
User m1 = new User();
MyUser m2 = new MyUser();
m2.setName(m1.getName());
m2.setsurmame(m1.getsurname());
...and so on...
Does anybody know a different way to do this kind of stuff?
Use Object Composition For objects that you create using the other library, create an instance of ExternalUser. But if you want to create them locally, create a BrandNewUser. Then you can just treat them the same way, with one version using the pass-through composition methods, and the ones created by your code using your own internal implementation.
You can create your object like this:
public interface MyUser {
// all the methods you need
String getSurname();
}
public class ExternalUser implements MyUser {
private User _user;
private ExternalUser() { }
public ExternalUser(User u) {
this._user = u;
}
public String getSurname() {
return _user.getSurname();
}
}
public class BrandNewUser implements MyUser {
private String _surname;
public ExternalUser(String name, String surname) {
this._surname = surname;
}
public String getSurname() {
return _surname;
}
}
There is a AutoMapper project in C Sharp.
In the gist of it it provides an easy way of mapping properties from a source instance to a destination instance where the source and destination instances can be of different classes.
this link shares some interesting thoughts about similar projects in Java : Automapper for Java
One thing you can do is pass that User object in a method of MyUser class or constructor of MyUser class and then perform those setters.
Using constructor :
public MyUser(User u){
setName(u.getName());
setSurname(u.getSurname());
...
}
Or creating a seperate method :
public void setMyUser(User u){
setName(u.getName());
setSurname(u.getSurname());
...
}
Then you can use it like this:
User u = new User();
//hope all values are set in User u object
MyUser m = new MyUser(u);
In cases where appropriate, refactor those objects to inherit from each other, rather than duplicate properties and logic.
In cases where the objects must remain distint, you can use any one of a variety of clone tools to perform deep copies from object to object. Here is a decent, non-exhaustive list:
Orika
Dozer
PropertyUtils
Maybe you can use beanutils which provides copy properties function.
http://commons.apache.org/beanutils/

which java collection object is best when persisting entities using jpa

I am writing an application that parses n number of records each with m number of fields. It is similar to parsing header information out of ip packets. One difference is that the records I'm working with have arrays of fields for optional user comments. My question is, what is the best java.util.collection object for persisting a collection of fields? A set is probably best for what I'm trying to do, because of multiple 'comment' fields that must be unique, but are there any performance or serialization concerns when choosing one collection type over another? Below is psedo-code for what I'm trying to do:
#Entity
public class MyRecord implements Serializable{
#Id
private int id;
private String filename;
#OneToMany(targetEntity=MyField.class, mappedBy="filename")
private Set<MyField> field;
}
public class MyField implements Serializable{
private int id;
private String filename;
private String filePath;
private String fieldName;
private String fieldType;
private String fieldValue;
}
You can take control by yourself for ultimate serialization performance, have a look at the Externalizable interface ( http://docs.oracle.com/javase/7/docs/api/java/io/Externalizable.html )
You can use Collection to be prepared for future changes. Maybe someday MyField is allowed to be not unique.

Categories

Resources