elegant object hierarchy - java

firstly, pardon my pseudo-code, i think in this case it is more legible than full code. Please assume that a property in the pseudo-code is in fact a field with a getter & setter method, except for the ArticleElement where it just needs be a property accessible from the object either by a direct getter method, or a two step getter method (ie getArticleSource().getName()).
Say i have a template entity:
ArticleTemplate
Long id;
String name;
String description;
Integer amount;
Schedule schedule;
and it is used (via its schedule) to create many potential children entities on different dates:
Article
Long id;
String name;
String description;
Integer amount;
Date date;
Boolean complete;
ArticleTemplate template;
some children entities are not created from a parent, they can be stand-alone (template can be null).
for my UI I want to create a sorted & merged list of :
a) potential children entities from parent entities
b) real children entities previously created from parent entities
c) orphan children entities created stand-alone
however, I need to add some properties to the elements of this list to determine the differences between the elements:
ArticleElement
// actual value if from Article, null if from potential from ArticleTemplate
Long id;
// actual value if from Article or ArticleTemplate
String name;
// actual value if from Article or ArticleTemplate
String description;
// actual value if from Article or ArticleTemplate
Integer amount;
// actual value if from Article, simulated if from potential from ArticleTemplate
Date date;
// actual value if from Article, false if from potential from ArticleTemplate
Boolean complete;
// actual value (nullable) if from Article, self if from potential from ArticleTemplate
ArticleTemplate template;
// false if from Article, true if from potential from ArticleTemplate
Boolean templateSimulation;
// once the list is sorted, a running tally of this.amount is to be stored on this object
Integer runningTally;
// would be type of interface if Article and ArticleTemplate implement same
Object source;
Clearly I'm going to have at least 3 classes but there's a few different approaches with interfaces etc.
I'd like to avoid cloning and property copying wherever possible, and use inheritence wherever beneficial.
suggestions appreciated!
p.

Here's my current solution, and i'm not sure I like it, but i haven't come up with anything better just yet:
firstly, i'll leave Article and ArticleTemplate alone. I could make them implement an interface describing their similarities but it doesn't add much benefit for this case.
create the UI contract
public interface UiElement<T>
{
T getSource();
Class<T> getType();
// redundant - refer to source
// Long getId();
String getName();
String getDescription();
Integer getAmount();
Date getDate();
Boolean getComplete();
// redundant - not needed anymore
// ArticleTemplate getTemplate();
// redundant - replaced by getType()
// Boolean getTemplateSimulation();
Integer getRunningTally();
}
create implementation for Article - pass through contracted calls to the source object for most properties
public class ArticleUiElement implements UiElement<Article>
{
private Article source;
private Integer tally;
public ArticleUiElement(Article source) {
this.source = source;
}
public Article getSource() {
return source;
}
public Class<Article> getType() {
return Article.class;
}
public String getName() {
return source.getName();
}
public String getDescription() {
return source.getDescription();
}
public Integer getAmount() {
return source.getAmount();
}
public Date getDate() {
return source.getDate();
}
public Boolean getComplete() {
return source.getComplete();
}
public String getRunningTally() {
return tally;
}
public void setRunningTally(String tally) {
this.tally = tally;
}
}
create implementation for ArticleTemplate - pass through contracted calls to the source object for most properties
public class ArticleTemplateUiElement implements UiElement<ArticleTemplate>
{
private ArticleTemplate source;
private Integer tally;
private Date date;
public ArticleTemplateUiElement(ArticleTemplate source) {
this.source = source;
}
public ArticleTemplate getSource() {
return source;
}
public Class<ArticleTemplate> getType() {
return ArticleTemplate.class;
}
public String getName() {
return source.getName();
}
public String getDescription() {
return source.getDescription();
}
public Integer getAmount() {
return source.getAmount();
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public Boolean getComplete() {
return false;
}
public String getRunningTally() {
return tally;
}
public void setRunningTally(String tally) {
this.tally = tally;
}
}
can someone offer improvements, or an entirely better solution?

Related

Is it correct to have static factory method to get a new instance with one field updated?

I think the title is self-descriptive but I will give an example to elaborate on my question. I have a DTO class with few fields (a CarDataTransferObj class in my example). In another class (let's call it class A) I need to create a new instance of that object few times, but with only one field updated (length field in my example). Given DTO must be immutable in class A. As there is "many" fields in the class CarDataTransferObj, I thought about following approach (to avoid repeating code in class A):
#Builder
public class CarDataTransferObj {
private Integer id;
private String color;
private String manufacturer;
private String model;
private String uniqueIdNr;
private Integer nrOfDoors;
private EngineType engineType;
private Integer length;
private Integer safetyLevel;
public static CarDataTransferObj newInstanceWithUpdatedLength(final CarDataTransferObj car, final Integer newLength) {
return CarDataTransferObj.builder()
.id(car.getId())
.color(car.getColor())
.manufacturer(car.getManufacturer())
.model(car.getModel())
.uniqueIdNr(car.getUniqueIdNr())
.nrOfDoors(car.getNrOfDoors())
.engineType(car.getEngineType())
.length(newLength)
.safetyLevel(car.getSafetyLevel())
.build();
}
}
For me it smells like a little anti-pattern usage of static factory methods. I am not sure whether it's acceptable or not, hence the question.
Is using static factory method in the presented way an anti-pattern, and should be avoided ?
In my searching, I didn't come across anyone calling this1 an anti-pattern.
However, it is clear that if you try to do this using a classic builder that is not specifically implemented to support this mode of operation .... it won't work. For instance, the example CarBuilderImpl in the Wikipedia article on the Builder design pattern puts the state into an eagerly created Car instance. The build() method simply returns that object. If you tried to reuse that builder in the way that you propose, you would end up modifying a Car that has already been built.
There is another problem you would need to worry about. In we modified the Wikipedia CarBuilder example to add actual wheels (rather than a number of wheels) to the Car being built, we have to worry about creating cars that share the same wheels.
You could address these things in a builder implementation, but it is unclear whether the benefits out-weigh the costs.
If you then transfer this thinking to doing this using a factory method, you come to a slightly different conclusion.
If you are doing this as a "one-off", that's probably OK. You have a specific need, the code is clunky ... but so is the problem.
If you needed to do this for lots of different parameters, or combinations of parameters, this is not going to scale.
If the objects that are created are mutable, then this approach is could be problematic in a multi-threaded environment depending on how you control access to the objects you are using as templates.
1 - There are no clear measurable criteria for whether something is an anti-pattern or not. It is a matter of opinion. Admittedly, for many anti-patterns, there will be wide-scale agreement on that opinion.
It seems a little inefficient to construct an entirely new instance via a builder every time you want to make a new copy with a small modification. More significantly, it sounds like the places where you need the class to be immutable are isolated to places like class A. Why not try something like this:
public interface ICarDataTransferObject {
public Integer GetId();
public String GetColor();
public String GetManufacturer();
public String GetModel();
public String GetUUID();
public Integer GetDoorCount();
public EngineType GetEngineType();
public Integer GetLength();
public Integer GetSafteyLevel();
}
public class CarDataTransferObject Implements ICarDataTransferObject {
private Integer _id;
private String _color;
private String _manufacturer;
private String _model;
private String _uniqueIdNr;
private Integer _nrOfDoors;
private EngineType _engineType;
private Integer _length;
private Integer _safetyLevel;
public Integer GetId() { return _id; }
public void SetId(Integer id) { _id = id; }
public String GetColor() { return _color; }
public void SetColor(String color) { _color = color; }
public String GetManufacturer() { return _manufacturer; }
public void SetManufacturer(String manufacturer) { _manufacturer = manufacturer; }
public String GetModel() { return _model; }
public void SetModel(String model) { _model = model; }
public String GetUUID() { return _uniqueIdNr; }
public void SetUUID(String uuid) { _uniqueIdNr = uuid; }
public Integer GetDoorCount() { return _nrOfDoors; }
public void SetDoorCount(Integer count) { _nrOfDoors = count; }
public EngineType GetEngineType() { return _engineType; }
public void SetEngineType(EngineType et) { _engineType = et; }
public Integer GetLength() { return _length; }
public void SetLength(Integer length) { _length = length; }
public Integer GetSafteyLevel() { return _safetyLevel; }
public void SetSafteyLevel(Integer level) { _safteyLevel = level; }
public CarDataTransferObject() {}
public CarDataTransferObject(ICarDataTransferObject other) { ... }
public ReadOnlyCarDataTransferObject AsReadOnly() {
return ReadOnlyCarDataTransferObject (this);
}
}
}
public class ReadOnlyCarDataTransferObject Implements ICarDataTransferObject {
private ICarDataTransferObject _dto = null;
public Integer GetId() { return _dto.GetId(); }
public String GetColor() { return _dto.GetColor(); }
public String GetManufacturer() { return _dto.GetManufacturer(); }
public String GetModel() { return _dto.GetModel(); }
public String GetUUID() { return _dto.GetUUID(); }
public Integer GetDoorCount() { return _dto.GetDoorCount(); }
public EngineType GetEngineType() { return _dto.GetEngineType(); }
public Integer GetLength() { return _dto.GetLength(); }
public Integer GetSafteyLevel() { return _dto.GetSafteyLevel; }
public ReadOnlyCarDataTransferObject (ICarDataTransferObject other) {
_dto = other;
}
}
Now when you want class A to have a copy no one can modify, just use the copy constructor and only expose a ReadOnly version of that copy.
public class A {
ICarDataTransferObject _dto;
ReadOnlyCarDataTransferObject _readOnlyDTO;
public ICarDataTransferObject GetDTO() { return _readOnlyDTO; }
public A(ICarDataTransferObject dto) {
_dto = new CarDataTransferObject(dto);
_readOnlyDTO = new ReadOnlyCarDataTransferObject(_dto);
}
}
You commonly see this approach in .NET applications.
While it is debatable whether your static method is an anti-pattern or not, it surely won't scale for combinations of different attributes. Nonetheless, even if it's not an anti-pattern, I think there is a better way to accomplish what you need.
There's a variant of the traditional builder pattern that, instead of creating a new empty builder, accepts an already built object and creates an already initialized builder. Once you create the builder this way, you simply change the length attribute in the builder. Finally, build the object. In plain code (no Lombok, sorry) it could be like this:
public class CarDataTransferObj {
private Integer id;
private String color;
// other attributes omitted for brevity
private Integer length;
// Private constructor for builder
private CarDataTransferObj(Builder builder) {
this.id = builder.id;
this.color = builder.color;
this.length = builder.length;
}
// Traditional factory method to create and return builder
public static Builder builder() {
return new Builder();
}
// Factory method to create and return builder initialized from an instance
public static Builder builder(CarDataTransferObj car) {
Builder builder = builder();
builder.id = car.id;
builder.color = car.color;
builder.length = car.length;
return builder;
}
// getters
public static class Builder {
private Integer id;
private String color;
private Integer length;
private Builder() { }
public Builder withId(Integer id) { this.id = id; return this; }
public Builder withColor(String color) { this.color = color; return this; }
public Builder withLength(Integer length) { this.length = length; return this; }
public CarDataTransferObj build() {
return new CarDataTransferObj(this);
}
}
}
Now with all this infrastructure in place, you can do what you want as easy as:
CarDataTransferObj originalCar = ... // get the original car from somewhere
CarDataTransferObj newCar = CarDataTransferObj.builder(originalCar)
.withLength(newLength)
.build();
This approach has the advantage that it scales well (it can be used to change any combination of parameters). Maybe all this builder's code seems boilerplate, but I use an IntelliJ plugin to create the builder with two keystrokes (including the variant factory method that accepts a built instance to create an initialized builder).
I'm still new to java but..
I guess making a copy method which takes the CarDataTransferObj object variables and sets their values to another CarDataTransferObj object variables and changing the the length using it's setter method would be better idea
Example:
public class CarDataTransferObj {
private Integer id;
private String color;
private String manufacturer;
private String model;
private String uniqueIdNr;
private Integer nrOfDoors;
private EngineType engineType;
private Integer length;
private Integer safetyLevel;
public void Copy(CarDataTransferObj copy) { //Could add another parameter here to be the new length
copy.setId(id);
copy.set(color);
copy.setManufacturer(manufacturer);
copy.setModel(model);
copy.setUniqueIdNr(uniqueIdNr));
copy.setNrOfDoors(nrOfDoors));
copy.setEngineType(engineType));
copy.setLength(length);
copy.setSafetyLevel(safetyLevel));
}
}
public class SomeOtherClass {
CarDataTransferObj car1 = new CarDataTransferObj(); //Using this way made you able to use the constructor for a more useful thing
//You set the variables you want for car1 here
CarDataTransferObj car2 = new CarDataTransferObj();
car1.Copy(car2)
car2.setLength(newLength) //Set the new length here
}

What is good practice to create pojo as having Class fields or simple

What is good practice to create pojo as having Class fields or simple fields.
I am creating pojo like this.
public class StatusDTO {
private String id;
private int totalNodes;
private int totalServlets;
private boolean status;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public int getTotalNodes() {
return totalNodes;
}
public void setTotalNodes(int totalNodes) {
this.totalNodes = totalNodes;
}
public int getTotalServlets() {
return totalServlets;
}
public void setTotalServlets(int totalServlets) {
this.totalServlets = totalServlets;
}
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
}
someone recommanded me to do like this as below
public class StatusDTO {
private String id;
private boolean status;
private Total total;
public Total getTotal() {
return total;
}
public void setTotal(Total total) {
this.total = total;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
public static class Total {
private int nodes;
private int servlets;
public int getNodes() {
return nodes;
}
public void setNodes(int nodes) {
this.nodes = nodes;
}
public int getServlets() {
return servlets;
}
public void setServlets(int servlets) {
this.servlets = servlets;
}
}
}
what difference does it make? what is good practice among those two?
I am using this class to set db info and send info to web socket client(stomp)
The answer, as always in such questions, is: It depends.
Simple classes like the first one have the advantage that they are simpler and smaller. The advantage on the second attempt is that if your class, maybe now, maybe later, gets extended, it might be easier if you create a separate Total class.
Good Objectoriented Programming, and Java is strongly OO, almost always requires you to put everything into it's own class.
As a rule of thumb, I create a separate class if:
there is some functionality you to your fields.
you have more then two, mabye three fields related to each other (e.g. connectionHost, connectionPort)
it's just a model class (e.g. Customer, Article)
I can use the field in multiple other classes
Of course there are more but those are some of the most important ones (comment if you think there is another important one I forgot to mention).
Well, one important thing in a good Java application is separation of concerns, for example in an airport application a service that give the last flight of a customer should not require as parameter an object with the first name, the last name, the social security number, the marital status, the gender or whatever other information about the customer that are completely useless (or should be) in retrieving the customer last flight, such that you need to have an object Customer (with all customer information) and another object CustomerId (with only the necessary bits to get the flights).
Another example is for a online shop application, a service that calculate the total price of the basket should not require all the information about all articles (photos, description, specifications, ...) in the basket but only the prices and the discounts which should be enclosed in another object.
Here you have to decide if the concerns of your Total (you need a better name) object could be taken separately of the concerns of your StatusDTO object, such that a method could require only the Total object without the associated StatusDTO object. If you can take them separately then you should have separate objects, if you can't then it's unnecessary.

Should getters have validation in java? [duplicate]

This question already has answers here:
Can I write validation logic in setter methods?
(7 answers)
Closed 7 years ago.
Should getters have validation in java(for example. checking if something is null)? or should they simply get whatever it is suppose to get with one return statement. To me this is how i usually do it.
public class GetterDemo
{
private String name;
private int age;
public GetterDemo(String name, int age)
{
this.name = name;
this.age = age;
}
public String getName()
{
return this.name;
}
public int getAge()
{
return this.age;
}
}
Now suppose that the constructor has an array of hobbies from a class called hobbies.
public class Hobbies
{
private String hobby;
private String category;
public Hobbies(String hobby, String category)
{
this.hobby = hobby;
this.category = category;
}
public String getHobby()
{
return this.hobby;
}
public String getCategory()
{
return this.category;
}
}
Now, lets update version of GetterDemo with an array of hobbies in the constructor as i said above. and it has a next method to get the next hobby in the array everytime its called.
public class GetterDemo
{
private String name;
private int age;
private int count = 0;
private Hobbies[] hobbies;
public GetterDemo(String name, int age, Hobbies[] hobbies)
{
this.name = name;
this.age = age;
this.hobbies = hobbies
}
public Hobbies getNextHobby()
{
//Create a counter.
Hobbies result;
if (this.hobbies == null || this.hobbies.length == 0
|| this.count >= this.hobbies.length) //Called more then length times.
return null;
result = this.hobbies[count];
count++;
return result;
}
public String getName()
{
return this.name;
}
public int getAge()
{
return this.age;
}
public void reset()
{
this.count = 0;
}
}
Okay so thats a little code example. There might be errors, probably many as I blankly coded it.
To explain in terms of testing for null(JUnit testing). If I call getNextHobby() hobby length times or more it will return null and I can AssertNull() and it will pass. However, for example, if I do AssertNull where the array of hobbies is Null and I try getNextHobby.getCategory(), it will throw a NullPointerException even though I want it to be null. Would the only way to fix this would be to create a method that checks for this? or a getter that checks for null somehow? Possibly the code below?
public boolean checkNull()
{
boolean result = false;
if (getNextHobby().getCategory() == null || getNextHobby().getHobby())
result = true;
return result;
}
I assume that it is a matter of taste.
I prefer that setters and getters do only what they suppose to do which means set some value or get some value. My reasons are the following:
The signature of the method should explain what this method is doing and as we know good method should do one thing well. Thus when you start adding some validation I would assume that you need to change the signature otherwise the caller might assume that only set/get operation happens.
Every IDE has an opportunity to generate getters and setters and for some reason they don't generate some validations for the parameters of the getter method thus I assume that you shouldn't do it as well.
I try to separate getters and setters from other methods, thus if I need to kind of get the value, however, it is not exactly a getter because you need to do some other actions, I prefer to use other words like fetch, retrieve, obtain. In this case it will be very clear that you don't need to test getters and setters because they don't really do anything, however, fetch and others you must.

Java equals() and hashcode() during automatic code generation

I am working on a project where code gets automatically generated based upon an MySQL library. It is somewhat like JPA, but not quite.
This is an example bean:
public class TemplateBean implements Bean {
private Integer templateId;
private Integer businessPartnerId;
public TemplateBean(final Integer businessPartnerId) {
this.businessPartnerId = businessPartnerId;
}
private TemplateBean(final Object nullObject, final Integer templateId, final Integer businessPartnerId) {
this.templateId = templateId;
this.businessPartnerId = businessPartnerId;
}
public TemplateBean(final ResultSet rs) throws SQLException {
this(null, rs.getInt(1), rs.getInt(2));
}
public Integer getTemplateId() {
return templateId;
}
public void setTemplateId(final Integer templateId) {
this.templateId = templateId;
}
public Integer getBusinessPartnerId() {
return businessPartnerId;
}
public void setBusinessPartnerId(final Integer businessPartnerId) {
this.businessPartnerId = businessPartnerId;
}
#Override
public String toString() {
return "Template(" + templateId + ", " + businessPartnerId + ")";
}
}
Now I need it to implement equals() and hashCode(). I of course have access to all data that is available from SQL, so I think implementing equals() should be doable, but how am I going to create a good hashCode()?
Any tips will be appreciated.
I would like to suggest to use EqualsBuilder
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
public class Person {
private String id;
private String name;
private String address;
private String phone;
private String version;
#Override
public boolean equals(Object object) {
return EqualsBuilder.reflectionEquals(this, object,);
}
#Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
or
/*
* equal() method with exclude fields.
* it will neglect id and version fields.
*
* */
#Override
public boolean equals(Object object) {
return EqualsBuilder.reflectionEquals(this, object, "id", "version");
}
}
One very convenient way is to use the #EqualsAndHashCode annotation provided by Groovy. Using this is as simple as
#EqualsAndHashCode
public class TemplateBean implements Bean {
// implementation omitted
}
This will generate equals() and hashCode() methods based on the class' properties using an algorithm similar to the one outlined in the book Effective Java.
Because the annotation is implemented via an AST transformation, it can be used in Java or Groovy classes, though you will of course need the Groovy library on your classpath to use it.

How to create a POJO?

Recently I've started hearing about "POJOs" (Plain Old Java Objects). I googled it, but still don't understand the concept well. Can anyone give me a clear description of a POJO?
Consider a class "Person" with variables "id, name, address, salary" -- how would I create a POJO for this scenario? Is the code below a POJO?
public class Person {
//variables
People people = new People();
private int id;
private String name;
private String address;
private int salary;
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getAddress() {
return address;
}
public int getSalary() {
return salary;
}
public void setId() {
this.id = id;
}
public void setName() {
this.name = name;
}
public void setAddress() {
this.address = address;
}
public void setSalary() {
this.salary = salary;
}
}
A POJO is just a plain, old Java Bean with the restrictions removed. Java Beans must meet the following requirements:
Default no-arg constructor
Follow the Bean convention of getFoo (or isFoo for booleans) and setFoo methods for a mutable attribute named foo; leave off the setFoo if foo is immutable.
Must implement java.io.Serializable
POJO does not mandate any of these. It's just what the name says: an object that compiles under JDK can be considered a Plain Old Java Object. No app server, no base classes, no interfaces required to use.
The acronym POJO was a reaction against EJB 2.0, which required several interfaces, extended base classes, and lots of methods just to do simple things. Some people, Rod Johnson and Martin Fowler among them, rebelled against the complexity and sought a way to implement enterprise scale solutions without having to write EJBs.
Martin Fowler coined a new acronym.
Rod Johnson wrote "J2EE Without EJBs", wrote Spring, influenced EJB enough so version 3.1 looks a great deal like Spring and Hibernate, and got a sweet IPO from VMWare out of it.
Here's an example that you can wrap your head around:
public class MyFirstPojo
{
private String name;
public static void main(String [] args)
{
for (String arg : args)
{
MyFirstPojo pojo = new MyFirstPojo(arg); // Here's how you create a POJO
System.out.println(pojo);
}
}
public MyFirstPojo(String name)
{
this.name = name;
}
public String getName() { return this.name; }
public String toString() { return this.name; }
}
POJO:- POJO is a Java object not bound by any restriction other than those forced by the Java Language Specification.
Properties of POJO
All properties must be public setter and getter methods
All instance variables should be private
Should not Extend prespecified classes.
Should not Implement prespecified interfaces.
Should not contain prespecified annotations.
It may not have any argument constructors
Example of POJO
public class POJO {
private String value;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
A POJO is a Plain Old Java Object.
From the wikipedia article I linked to:
In computing software, POJO is an
acronym for Plain Old Java Object. The
name is used to emphasize that a given
object is an ordinary Java Object, not
a special object, and in particular
not an Enterprise JavaBean
Your class appears to already be a POJO.
POJO class acts as a bean which is used to set and get the value.
public class Data
{
private int id;
private String deptname;
private String date;
private String name;
private String mdate;
private String mname;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDeptname() {
return deptname;
}
public void setDeptname(String deptname) {
this.deptname = deptname;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMdate() {
return mdate;
}
public void setMdate(String mdate) {
this.mdate = mdate;
}
public String getMname() {
return mname;
}
public void setMname(String mname) {
this.mname = mname;
}
}
When you aren't doing anything to make your class particularly designed to work with a given framework, ORM, or other system that needs a special sort of class, you have a Plain Old Java Object, or POJO.
Ironically, one of the reasons for coining the term is that people were avoiding them in cases where they were sensible and some people concluded that this was because they didn't have a fancy name. Ironic, because your question demonstrates that the approach worked.
Compare the older POD "Plain Old Data" to mean a C++ class that doesn't do anything a C struct couldn't do (more or less, non-virtual members that aren't destructors or trivial constructors don't stop it being considered POD), and the newer (and more directly comparable) POCO "Plain Old CLR Object" in .NET.
According to Martin Fowler
The term was coined while Rebecca Parsons, Josh MacKenzie and I were preparing for a talk at a conference in September 2000. In the talk, we were pointing out the many benefits of encoding business logic into regular java objects rather than using Entity Beans. We wondered why people were so against using regular objects in their systems and concluded that it was because simple objects lacked a fancy name. So we gave them one, and it’s caught on very nicely.
Generally, a POJO is not bound to any restriction and any Java object can be called a POJO but there are some directions. A well-defined POJO should follow below directions.
Each variable in a POJO should be declared as private.
Default constructor should be overridden with public accessibility.
Each variable should have its Setter-Getter method with public accessibility.
Generally POJO should override equals(), hashCode() and toString() methods of Object (but it's not mandatory).
Overriding compare() method of Comparable interface used for sorting (Preferable but not mandatory).
And according to Java Language Specification, a POJO should not have to
Extend pre-specified classes
Implement pre-specified interfaces
Contain pre-specified annotations
However, developers and frameworks describe a POJO still requires the use prespecified annotations to implement features like persistence, declarative transaction management etc. So the idea is that if the object was a POJO before any annotations were added would return to POJO status if the annotations are removed then it can still be considered a POJO.
A JavaBean is a special kind of POJO that is Serializable, has a no-argument constructor, and allows access to properties using getter and setter methods that follow a simple naming convention.
Read more on Plain Old Java Object (POJO) Explained.
there are mainly three options are possible for mapping purpose
serialize
XML mapping
POJO mapping.(Plain Old Java Objects)
While using the pojo classes,it is easy for a developer to map with the database.
POJO classes are created for database and at the same time value-objects classes are created with getter and setter methods that will easily hold the content.
So,for the purpose of mapping in between java with database, value-objects and POJO classes are implemented.
import java.io.Serializable;
public class Course implements Serializable {
protected int courseId;
protected String courseName;
protected String courseType;
public Course() {
courseName = new String();
courseType = new String();
}
public Course(String courseName, String courseType) {
this.courseName = courseName;
this.courseType = courseType;
}
public Course(int courseId, String courseName, String courseType) {
this.courseId = courseId;
this.courseName = courseName;
this.courseType = courseType;
}
public int getCourseId() {
return courseId;
}
public void setCourseId(int courseId) {
this.courseId = courseId;
}
public String getCourseName() {
return courseName;
}
public void setCourseName(String courseName) {
this.courseName = courseName;
}
public String getCourseType() {
return courseType;
}
public void setCourseType(String courseType) {
this.courseType = courseType;
}
#Override
public int hashCode() {
return courseId;
}
#Override
public boolean equals(Object obj) {
if (obj != null || obj instanceof Course) {
Course c = (Course) obj;
if (courseId == c.courseId && courseName.equals(c.courseName)
&& courseType.equals(c.courseType))
return true;
}
return false;
}
#Override
public String toString() {
return "Course[" + courseId + "," + courseName + "," + courseType + "]";
}
}
public class UserInfo {
String LoginId;
String Password;
String FirstName;
String LastName;
String Email;
String Mobile;
String Address;
String DOB;
public String getLoginId() {
return LoginId;
}
public void setLoginId(String loginId) {
LoginId = loginId;
}
public String getPassword() {
return Password;
}
public void setPassword(String password) {
Password = password;
}
public String getFirstName() {
return FirstName;
}
public void setFirstName(String firstName) {
FirstName = firstName;
}
public String getLastName() {
return LastName;
}
public void setLastName(String lastName) {
LastName = lastName;
}
public String getEmail() {
return Email;
}
public void setEmail(String email) {
Email = email;
}
public String getMobile() {
return Mobile;
}
public void setMobile(String mobile) {
Mobile = mobile;
}
public String getAddress() {
return Address;
}
public void setAddress(String address) {
Address = address;
}
public String getDOB() {
return DOB;
}
public void setDOB(String DOB) {
this.DOB = DOB;
}
}
File-setting-plugins-Browse repositories
Search RoboPOJOGenerator and install, Restart Android studio
Open Project and right click on package select on Generate POJO from JSON
Paste JSON in dialogbox and select option according your requirements
Click on Generate button
If a class is not bogged down from a framework or a library, then an object created from that class is recognized as a POJO.
Let's see some examples:
class MyServlet extends HttpServlet{
//....
}
The sole meaning of MyServlet class is given by the HttpServlet class. Therefore the objects created from the MyServlet are not POJOs.
class MyClass implements Serializable{
//...
}
The Serializable interface does not give a meaning to the class MyClass. Therefore the objects created from the MyClass are POJOs.

Categories