What does the term Plain Old Java Object (POJO) mean? I couldn't find anything explanatory enough.
POJO's Wikipedia page says that POJO is an ordinary Java Object and not a special object. Now, what makes or what doesn't make and object special in Java?
The above page also says that a POJO should not have to extend prespecified classes, implement prespecified Interfaces or contain prespecified Annotations. Does that also mean that POJOs are not allowed to implement interfaces like Serializable, Comparable or classes like Applets or any other user-written Class/Interfaces?
Also, does the above policy (no extending, no implementing) means that we are not allowed to use any external libraries?
Where exactly are POJOs used?
EDIT: To be more specific, am I allowed to extend/implement classes/interfaces that are part of the Java or any external libraries?
Plain Old Java Object The name is used to emphasize that a given object is an ordinary Java Object, not a special object such as those defined by the EJB 2 framework.
class A {}
class B extends/implements C {}
Note: B is non POJO when C is kind of distributed framework class or ifc.
e.g. javax.servlet.http.HttpServlet, javax.ejb.EntityBean or J2EE extn
and not serializable/comparable. Since serializable/comparable are valid for POJO.
Here A is simple object which is independent.
B is a Special obj since B is extending/implementing C. So B object gets some more meaning from C and B is restrictive to follow the rules from C. and B is tightly coupled with distributed framework. Hence B object is not POJO from its definition.
Code using class A object reference does not have to know anything about the type of it, and It can be used with many frameworks.
So a POJO should not have to 1) extend prespecified classes and 2) Implement prespecified interfaces.
JavaBean is a example 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.
POJO purely focuses on business logic and has no dependencies on (enterprise) frameworks.
It means it has the code for business logic but how this instance is created, Which service(EJB..) this object belongs to and what are its special characteristics( Stateful/Stateless) it has will be decided by the frameworks by using external xml file.
Example 1: JAXB is the service to represent java object as XML; These java objects are simple and come up with default constructor getters and setters.
Example 2: Hibernate where simple java class will be used to represent a Table. columns will be its instances.
Example 3: REST services. In REST services we will have Service Layer and Dao Layer to perform some operations over DB. So Dao will have vendor specific queries and operations. Service Layer will be responsible to call Which DAO layer to perform DB operations. Create or Update API(methods) of DAO will be take POJOs as arguments, and update that POJOs and insert/update in to DB. These POJOs (Java class) will have only states(instance variables) of each column and its getters and setters.
In practice, some people find annotations elegant, while they see XML as verbose, ugly and hard to maintain, yet others find annotations pollute the POJO model.
Thus, as an alternative to XML, many frameworks (e.g. Spring, EJB and JPA) allow annotations to be used instead or in addition to XML:
Advantages:
Decoupling the application code from the infrastructure frameworks is one of the many benefits of using POJOs. Using POJOs future proofs your application's business logic by decoupling it from volatile, constantly evolving infrastructure frameworks. Upgrading to a new version or switching to a different framework becomes easier and less risky. POJOs also make testing easier, which simplifies and accelerates development. Your business logic will be clearer and simpler because it won't be tangled with the infrastructure code
References : wiki source2
According to Martin Fowler, he and some others came up with it as a way to describe something which was a standard class as opposed to an EJB etc.
Usage of the term implies what it's supposed to tell you. If, for example, a dependency injection framework tells you that you can inject a POJO into any other POJO they want to say that you do not have to do anything special: there is no need to obey any contracts with your object, implement any interfaces or extend special classes. You can just use whatever you've already got.
UPDATE To give another example: while Hibernate can map any POJO (any object you created) to SQL tables, in Core Data (Objective C on the iPhone) your objects have to extend NSManagedObject in order for the system to be able to persist them to a database. In that sense, Core Data cannot work with any POJO (or rather POOCO=PlainOldObjectiveCObject) while Hibernate can. (I might not by 100% correct re Core Data since I just started picking it up. Any hints / corrections are welcome :-) ).
Plain Old Java Object :)
Well, you make it sound like those are all terrible restrictions.
In the usual context where POJO is/are used, it's more like a benefit:
It means that whatever library/API you're working with is perfectly willing to work with Java objects that haven't been doctored or manhandled in any way, i.e. you don't have to do anything special to get them to work.
For example, the XStream XML processor will (I think) happily serialize Java classes that don't implement the Serializable interface. That's a plus! Many products that work with data objects used to force you to implement SomeProprietaryDataObject or even extend an AbstractProprietaryDataObject class. Many libraries will expect bean behavior, i.e. getters and setters.
Usually, whatever works with POJOs will also work with not-so-PO-JO's. So XStream will of course also serialize Serializable classes.
POJO is a Plain Old Java Object - as compared to something needing Enterprise Edition's (J2EE) stuff (beans etc...).
POJO is not really a hard-and-fast definition, and more of a hand-wavy way of describing "normal" non-enterprise Java Objects. Whether using an external library or framework makes an object POJO or not is kind of in the eye of the beholder, largely depending on WHAT library/framework, although I'd venture to guess that a framework would make something less of a POJO
The whole point of a POJO is simplicity and you appear to be assuming its something more complicated than it appears.
If a library supports a POJO, it implies an object of any class is acceptible. It doesn't mean the POJO cannot have annotations/interface or that they won't be used if they are there, but it is not a requirement.
IMHO The wiki-page is fairly clear. It doesn't say a POJO cannot have annotations/interfaces.
What does the term Plain Old Java Object (POJO) mean?
POJO was coined by Martin Fowler, Rebecca Parsons and Josh Mackenzie when they were preparing for a talk at a conference in September 2000. Martin Fowler in Patterns of Enterprise Application Architecture explains how to implement a Domain Model pattern in Java. After enumerating some of disadvantages of using EJB Entity Beans:
There's always a lot of heat generated when people talk about
developing a Domain Model in J2EE. Many of the teaching materials and
introductory J2EE books suggest that you use entity beans to develop a
domain model, but there are some serious problems with this approach,
at least with the current (2.0) specification.
Entity beans are most useful when you use Container Managed
Persistence (CMP)...
Entity beans can't be re-entrant. That is, if you call out from one
entity bean into another object, that other object (or any object it
calls) can't call back into the first entity bean...
...If you have remote objects with fine-grained interfaces you get
terrible performance...
To run with entity beans you need a container and a database
connected. This will increase build times and also increase the time
to do test runs since the tests have to execute against a database.
Entity beans are also tricky to debug.
As an alternative, he proposed to use Regular Java Objects for Domain Model implementation:
The alternative is to use normal Java objects, although this often
causes a surprised reaction—it's amazing how many people think that
you can't run regular Java objects in an EJB container. I've come to
the conclusion that people forget about regular Java objects because
they haven't got a fancy name. That's why, while preparing for a talk
in 2000, Rebecca Parsons, Josh Mackenzie, and I gave them one: POJOs
(plain old Java objects). A POJO domain model is easy to put together,
is quick to build, can run and test outside an EJB container, and is
independent of EJB (maybe that's why EJB vendors don't encourage you
to use them).
There is an abundance of posts that are half correct and half incorrect. The best example of the correct interpretation is given by Rex M in their answer here.
[POJO are classes] that doesn't require any significant "guts" to make
it work. The idea is in contrast with very dependent objects that have
a hard time being (or can't be) instantiated and manipulated on their
own - they require other services, drivers, provider instances, etc.
to also be present.
Unfortunately, these very same answers often come along with the misunderstanding that they are somehow simple or often have a simple structure. This is not necessarily true and the confusion seems to stem from the fact that in the Java (POJO) and C# world (POCO) business logic is relatively easily modeled especially in the web application world.
POJO's can have multiple levels of inheritance, generic types, abstractions, etc. It just so happens that this isn't required in the majority of web applications as business logic doesn't necessitate it - alot of the effort goes into databases, queries, data transfer objects and repositories.
As soon as you step out of line with simple web apps, your POJO's start looking a lot more complex. E.g. Make a web app that assigns taxi's to user schedules. To do this, you need a graph coloring algorithm. To color the graphs, you need a graph object. Each node in the graph is a schedule object. Now what if we want to make it generic so that coloring the graph can be done not only with schedules but other things as well. We can make it generic, abstract and add levels of inheritance - almost to the point of making it a mini library.
At this point though, no matter its complexity, its still a POJO because it doesn't rely on the guts of other frameworks.
A Plain Old Java Object (POJO) that contains all of the business logic for your extension.
Exp. Pojo which contains a single method
public class Extension {
public static void logInfo(String message) {
System.out.println(message);
}
}
Related
I want to start incorporating the practice of writing invariants for my classes. For my POJOs, is it a good practice to validate its state by validating it against business rules. Say I have
this class for instance:
#Data
public class Pick {
List<Substitution> substitutions = new ArrayList<>();
}
Now, my invariant says that every substitution object in the list needs to have a substitution reason. Is it a good practice to do such business checks inside POJOs that are meant to be simple data carriers?
Note that I already use #NonNull which is also an invariant, although a very basic one. Is it a good practice to write invariants that test for complex business relationships b/w your fields?
JSR 380 is a specification of the Java API for bean validation, part of Jakarta EE and JavaSE, which ensures that the properties of a bean meet specific criteria, using annotations such as #NotNull, #Min, and #Max.
We can see this approach used in Java ecosystem heavily, as far as it doesn't touch your business logic and also data object and keeps them clean it is goof
more here
The question is simple. I need to convert the content of a bean into an other bean with different getters and setters. What's the right design pattern for doing this?
I think an adapter pattern is mainly referring to a mapping of a signature or interface to an other. Not a real mapping between objects.
Many people talks about "mapper" but I think this is not a design pattern.
So, is there actually a pattern for mapping an object to an other?
I'm not aware of any popular design pattern for object mapping.
I have been using Dozer framework for transfering the content from one bean to another.
It is simple to use and easily integrates with Spring.
Refer:
http://dozer.sourceforge.net/documentation/gettingstarted.html
A great "design pattern" would be to not tightly couple the mapped objects to each other. A copy constructor, for example, means that if you edit the source class, you also have to edit the destination class, and that can cause all sorts of downstream issues in a large project. Think about it this way. A very frequent mapping is from UI data structures to back-end data structures. You should be able to scrap your UI and not have to change the back-end for a new UI. An MVC design pattern is frequently used for this sort of work.
There is a nice Translator pattern published by Microsoft. The tutorial is in C++ but it should be easy to convert to Java.
Here is a tutorial: http://richhewlett.com/2010/06/11/a-useful-entity-translator-pattern-object-mapper-template/
The general idea is you have a generic Translator abstract class, parametrized with the class types you want to translate between. The concrete implementations provide the "to" and "from" conversion methods.
This pattern has the advantage that it does not require coupling between the two classes in the conversion. It does this in a reusable, generic framework that won't clutter your code with one-off conversion decoupling logic.
The related pattern is Assembler where you assemble some object given the contents of another. Since writing assemblers can be tedious and error-prone, you can use an object mapping library to do the work for you.
One object mapper you might check out is ModelMapper, which I authored, that uses actual code to map properties, fields and methods, in a safe way.
I agree with Javakid, what you need is not a design pattern but a good solution to handle te conversion from one bean to another.
If you really need to name, that should something like dto pattern since you are using data transfer object. You can use a visitor to inspect all your bean tree while building the converted one.
so I would suggest using a framework or developping the mapping by yourself, it depends on the size of the graph. Dozer is goode solution to do it but it uses Reflection API all the way and hide the mapping code. So you won't be able to debug it easily, there are also few other runtime mapping library like Orika the best I know.
But, If you want to be able to see the code, debug it and have compiler feedback you can also use Selma.
Last thing, you can also report to this thread for a big picture of solutions to handle bean to bean mapping in java: any tool for java object to object mapping?
After comming from Ruby world, I'm having little problems doing TDD in Java. The biggest issue is when I have application that is just communicating with external API.
Say I want to just fetch some data from Google Calendar, or 5 tweets from some Twitter user and display it.
In Ruby, I don't have any problems, because I can monkey-patch the API library in tests directly, but I have no such option in Java.
If I think about this in terms of MVC, my model objects are directly accessing the API through some library. The question is, is this bad design? Should I always wrap any API library in some interface, so I can mock/stub it in Java?
Because when I think about this, the only purpose of that interface would be to simulate (please don't kill me for saying this) the monkey-patch. Meaning that any time I use any external resource, I have to wrap each layer in interface that can be stubbed out.
# do I have to abstract everything just to do this in Java?
Twitter.stub!(:search)
Now you might say that I should always abstract away the interface, so I can change the underlying layer to anything else. But if I'm writing twitter app, I'm not going to change it to RSS reader.
Yes, I can add for example Facebook and then it would make sense to have interface. But when there is no other resource that can be substituted for the one I'm using, than I still have to wrap everything in interfaces to make it testable.
Am I missing something, or is this just a way to test in the Java world?
Using interfaces is just generally good practice in Java. Some languages have multiple inheritance, others have duck typing, Java has interfaces. It's a key feature of the language, it lets me use
different aspects of a class in different contexts and
different implementations of the same contract without changing client code.
So interfaces are a concept you should embrace in general, and then you would reap the benefits in situations like this where you could substitute your services by mock objects.
One of the most important books about Java best practices is Effective Java by Joshua Bloch. I would highly suggest you to read it. In this context the most important part is Item 52: Refer to objects by their interfaces. Quote:
More generally, you should favor the use of interfaces rather than
classes to refer to objects. If appropriate interface types exist, then parameters, return values, variables, and fields should all be declared using interface
types. The only time you really need to refer to an object’s class is when you’re
creating it with a constructor.
And if you take things even further (e.g. when using dependency injection), you aren't even calling the constructor.
One of the key problems of switching languages is that you have to switch the way of thinking too. You can't program language x effectively while thinking in language y. You can't program C effectively without using pointers, Ruby not without duck typing and Java not without Interfaces.
Wrapping the external API is the way I would do this.
So, as you already said, you would have an interface and two classes: the real one and the dummy implementation.
Yes, it may seem unreasonable from the perspective of some services indeed being specific, like Twitter. But, this way your build process doesn't depend on external resources. Depending on external libraries isn't all that bad, but having your tests depend on actual data present or not present out there on the web can mess up the build process.
The easiest way is to wrap the API service with your interface/class pair and use that throughout your code.
I understand that what you want are Mock objects.
As you described it, one of the ways one can generate "test versions" of objects is by implementing a common interface and using it.
However, what you are missing is to simply extend the class (provided that it is not declared final) and override the methods that you want to mock. (NB: the possibility of doing that is the reason why it is considered bad form for a library to declare its classes final - it can make testing considerably harder.)
There is a number of Java libraries that aim in facilitating the use of Mock objects - you can look at Mockito or EasyMock.
Mockito is more handy and like your ruby mocks.
You can "monkey-patch" an API in Java. The Java language itself does not provide specific means to do it, but the JVM and the standard libraries do. In Ruby, developers can use the Mocha library for that. In Java, you can use the JMockit library (which I created because of limitations in older mocking tools).
Here is an example JMockit test, equivalent to the test_should_calculate_value_of_unshipped_orders test available in Mocha documentation:
#Test
public void shouldCalculateValueOfUnshippedOrders()
{
final Order anOrder = new Order();
final List<Order> orders = asList(anOrder, new Order(), new Order());
new NonStrictExpectations(Order.class)
{{
Order.findAll(); result = orders;
anOrder.getTotalCost(); result = 10;
}};
assertEquals(30, Order.unshippedValue());
}
Are the notions mentionned in the question title synonymous to a certain degree? Where do the main differences lie (context, structure, ...) and can one be considered a subset of another? Here's some brief definitions taken from Wikipedia.
POJO (Plain Old Java Object)
Wikipedia
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. The term
was coined by Martin Fowler, Rebecca
Parsons and Josh MacKenzie in
September 2000:
"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."
Java Bean Wikipedia
JavaBeans are reusable software
components for Java that can be
manipulated visually in a builder
tool. Practically, they are classes
written in the Java programming
language conforming to a particular
convention. They are used to
encapsulate many objects into a single
object (the bean), so that they can be
passed around as a single bean object
instead of as multiple individual
objects. A JavaBean is a Java Object
that is serializable, has a nullary
constructor, and allows access to
properties using getter and setter
methods.
Value Object Wikipedia
Data transfer object (DTO), formerly
known as value objects or VO, is a
design pattern used to transfer data
between software application
subsystems. DTOs are often used in
conjunction with data access objects
to retrieve data from a database.
Business Object Wikipedia
A business object is a type of an
intelligible entity being an actor
inside the business layer in a
n-layered object-oriented computer
program.
Related:
Difference between DTO, VO, POJO, JavaBeans?
What is the difference between a JavaBean and a POJO?
DDD: what's the use of the difference between entities and value objects?
Not all of these classifications are related. Here's my understanding:
POJO is what its name suggests - a plain old Java object. There's nothing special about it. And this is exactly what we want to convey when we say that an object is a POJO. Today most applications are using some kinds of underlying frameworks, and with the frameworks come requirements on the objects that will integrate with the framework - the object must implement an interface or extend a class. When we say an object is a POJO, we mean to say it is just an ordinary object and has no dependencies on any framework.
A JavaBean is a java class that follows certain conventions as described in your question. Such objects are often mandated by certain frameworks which use reflection to find out the properties (accessible through getters/setters) of the object and manipulate them e.g. beans exposed to JSPs, Spring beans etc. The good thing about JavaBeans is that they are still POJOs. Although they follow certain conventions, the conventions are not defined by any particular framework but are rather defined by Sun Javabean standard and the classes are still plain Java classes with no ties to any third party framework's classes or interfaces.
Business Objects refer to objects that represent your business domain entities. These usually reside in your business layer - the layer where all the business logic is. These objects usually map to persistence store entities e.g. tables. These objects could be POJOs, JavaBeans, EJBs etc.
Value objects are a type of design pattern. In some small web applications, you have the option of using your business objects in the web layer as well. However, in larger applications or J2EE applications, you define value objects to move information from the business layer to the web layer. That's why they are also called Data Transfer Objects (DTOs). These objects usually have only the attributes that are needed in the web layer and leave the attributes of business objects that were meant for business layer consumption behind. They may also have "computed" attributes that are generated in the business layer. Using this patterns helps decouple the business and web layers.
Here's my take:
Business objects is a generic term
for the abstract idea that
represents your problem. You can
implement them in any language. In
Java, you have additional choices to
make, because they can be POJOs or
EJBs, mutable or immutable.
Value objects or DTOs are used to ferry data between layers. They're usually immutable. They can be implemented as POJOs or Java Beans. Think of them as another subset of POJOs.
A Java Bean conforms to the original Sun specification. They were intended to provide an interface that would allow them to be plugged into a VB-style IDE with ease. Think of these as a subset of POJO.
People sometimes get confused about the difference between Java Beans and Enterprise Java Beans. Java Beans are part of the original Java 1.0 spec, intended to be like VB components (remember "Bean Box"?). Enterprise Java Beans were a spec that followed that described how special Java objects would implement specific interfaces to interoperate with a Java EE app server. The app server was a transaction monitor for a distributed component architecture that would handle threading, persistence, pooling, object lifecycle, messaging, naming, etc. EJBs are a very special subset of Java objects that work only within the context of a Java EE app server.
A POJO can be implemented to conform to the Java Bean standard, but it's not a requirement. Any Java object qualifies as a POJO. It was originally meant to distinguish them from EJB version 2.0, which required several interfaces in order to interoperate with the Java EE app server properly.
The questions is whether it's a mistake to use some of these as synonyms (like I've heard some people do) and if a given classification can be considered as a subset or another.
It is a mistake to use these terms as synonyms. They clearly have distinct meanings. The quoted definitions (and those provided in other answers) make this clear.
However, if it is often valid to use many (or even all) of these terms to describe the same object or objects. It is all a matter of perspective; i.e. what aspect of the object(s) you are trying to emphasize.
Synthesis (from answers given):
POJO: An ordinary object with no dependencies towards any framework. It can be adapted to conform to the Java Bean standard without being a requirement as such.
JavaBean: Object conforming to the Sun JavaBean or Java 1.0 specification (refer to "Bean box"). They were originally intended to provide an interface so they could be plugged into a VB-style IDE with little difficulty. Can be considered as a subset of POJOs and remain independant of frameworks. It can employ certain mecanisms such as reflection to access properties.
Enterprise Java Bean: These shouldn't be confused with Java Beans. With the simplifications brought about with version 3.0, EJBs can be considered as equivalent to a POJO. EJB in itself is a specification describing special Java Objects that can interoperate with a Java EE server. The server as such acted as a transaction monitor in the context of a distributed component architecture handling things such as threading, persistence, pooling, object lifecycle, messaging and naming. As such an EJB can be viewed as a very special subset that used in the contect of a Java EE application server.
Business object: Theoretical concept or abstract idea that helps to represent a given problem. It represents business domain entities and resides in the business layer of an application. They can be mapped to entities in the context of persistance. The object can be a POJO/JavaBean/EJB and be either mutable or immutable.
Value object/Data Transfer Object: Employs a design pattern which helps to decouple the business and web layers. This is to suit the context of large applications where objects can transit between layers (the business and web layer for example). They're usually immutable in nature and can either be formated as POJOs or Java Beans. One specificity is that they can contain computed attributes that are generated in the business layer.
P.S: Marked as community wiki so feel free to edit.
In general, is it a best practice to have simple POJO Java classes implement java.io.Serializable?
Generally not. Joshua Bloch says to implement Serializable judiciously. A summary of drawbacks that he describes:
decreases flexibility of changing class implementation later - the serialized form is part of the class's API
makes some bugs and security holes more likely - an attacker can access class internals within the serialized byte stream
increases test burden - now you have to test serialization!
burdens authors of subclasses - they have to make their subclasses Serializable too
Of course, sometimes you need a POJO to implement Serializable, say for RMI, but if the need isn't there, your code will be simpler and more secure without it.
Only if you need to be able to serialise them. It's not worth the effort otherwise.
It depends more on the needs. In the context of web applications, some web servers (eg. Tomcat 6) even make it mandatory to serialize the classes whose objects we store in sessions.
One thing I've done to address the fact that the serialized form is not backwards compatible (say when dynamically reloading a class on a running system), is load the fields I want to save into a hashmap and then serializing that. That way, I can always deserialize in the data, even if there are missing fields. You might have to provide defaults for missing keys, but it's better than messing up field order.