Alessandro Lacava

on Designing and Developing Software. In love with Functional Programming.

POJO (Plain Old Java Object): The simpler… The Better.

A POJO is simply an object built using a Java class that does not implement any special interfaces such as those defined by the EJB 2 framework. An example of a POJO is a class composed by only:

  1. Properties, representing the object’s state.
  2. Getter and setter methods for the properties.
  3. Business methods, representing behaviour.

Some properties can represent associations with other POJOs. Here is an example of implementation of the Person entity using a POJO:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class Person {
  //1. properties
  private String firstName;
  private String secondName;
  private Address address;

  //2. getters and setters
  public void setFirstName(String firstName) {
    this.firstName = firstName;
  }
  public String getFirstName() {
    return firstName;
  }
  // ... the other getters and setters

  //3. business methods
  public int computeAge() {
    //here the business logic to compute the person's age
  }
}

As you can see the address property represents an association to another hypothetical POJO.

That’s all! Code that handles database connections and so on shouldn’t be contained within a POJO.

There are many advantages in using POJOs. First of all they’re simple. Second they’re very suitable to represent domain models. Many tools, like Hibernate, work best with domain models implemented using POJOs.

Comments