Pojo class là gì

POCO – viết tắt của Plain Old CLR Object, hoặc Plain Old C# Object, Plain Old C++ Object,… là một thuật ngữ này bắt nguồn từ POJO [Plain Old Java Object]. Nếu bạn cảm thấy mơ hồ về khái niệm này, hãy cùng tôi tìm hiểu qua bài viết sau.

Note: Tên gọi của nó thay đổi dựa vào ngôn ngữ [hay nền tảng] mà nó được sử dụng để tạo ra nên có thể gọi chung là Plain Old Class Object. Thay cho CLR, nó còn có thể được gọi là PONO [Plain Old .NET Object].
Một lớp POCO phải tuân theo hai nguyên tắc sau:

Nguyên tắc 1: Chỉ dùng CLR

Theo tiếng Việt, bạn có thể dịch sát nghĩa nó là “Đối tượng thuần CLR/.NET cũ”. Giải thích ngắn gọn: POCO là lớp chỉ sử dụng các kiểu dữ liệu tiêu chuẩn của CLR. Bạn không được sử dụng các kiểu dữ liệu “ngoại lai” từ bất kì thư viện, framework nào nằm ngoài phạm vi chứa các POCO [có thể xác định là project]. Như vậy, một POCO có thể sử dụng các POCO khác miễn là nó cùng phạm vi.

[thecia.com.au]

POCO giống một ông lão “cổ hủ” sống cô lập.

Để thấy rõ ràng đặc điểm của POCO, bạn có thể thực hành một vài ví dụ Entity Framework theo mô hình Code First. Bạn có thể nhận ra rằng các lớp POCO được định nghĩa đơn giản nhất có thể. Chúng không cần phải thừa kế từ lớp nọ hay hiện thực một interface nào đó, hay có các attribute để xác định thêm các thông tin [metadata] cho việc mapping [như tên gọi, kiểu dữ liệu,…].

Dưới đây là hai lớp POCO đơn giản ánh xạ hai bảng trong database Northwind:

public class Category
{
    public int CategoryID { get; set; }
    public string CategoryName { get; set; }
    public string Description { get; set; }
    public IList Products { get; set; }
}

public class Product
{
    public int ProductID { get; set; }
    public string ProductName { get; set; }
    public Category Category { get; set; }
}

Lưu ý rằng không nên nhầm lẫn rằng POCO chỉ được dùng làm đối tượng chứa dữ liệu như các DTO [Data Transfer Object]. POCO có thể có các chức năng xử lý [hay behavior] cần thiết như tính toán, kiểm tra dữ liệu,… Tuy nhiên việc cung cấp các behavior cũng phải được giới hạn, tránh vi phạm nguyên tắc sau:
Nguyên tắc 2: Persistence Ignorance

Thuật ngữ này có một chút khó hiểu với từ “persistence”. Mò wikipedia, tôi được đoạn định nghĩa sau:

  
  In computer science, persistence refers to the characteristic of state that outlives the process that created it. Without this capability, state would only exist in RAM, and would be lost when this RAM loses power, such as a computer shutdown. [Wikipedia]

Cụm từ “characteristic of state” bạn có thể hiểu theo một từ quen thuộc là data. Tóm lại “persistence” được hiểu là các dữ liệu được nằm “cứng” trên ổ đĩa, có thể là database, hay một file chứa bất kì. Các dữ liệu này không phụ thuộc vào chương trình sử dụng.

Như vậy thuật ngữ “Persistence Ignorance” được hiểu: tránh “dính líu” đến nguồn dữ liệu [persistence]. Tức là các POCO sẽ không biết, không liên hệ, không có bất kì phương thức nào cho phép chúng truy xuất đến nguồn dữ liệu. POCO chỉ có nhiệm vụ chứa và xử lý dữ liệu.

Có thể hiểu nguyên tắc này khái quát hơn là: POCO ko nên có bất kì nhiệm vụ nào khác ngoài việc lưu trữ và xử lý dữ liệu [trên bộ nhớ]. Điều này đơn giản là tuân theo nguyên lý Single responsibility trong việc thiết kế hướng đối tượng [Mỗi lớp chỉ nên đảm nhận duy nhất và trọn vẹn một trách nhiệm/công việc ].

Chính vì vậy, khi sử dụng POCO, lập trình viên thường tạo một tầng Respository [pattern] để thao tác với nguồn dữ liệu.
Tại sao cần dùng POCO?

Một dự án có thể dùng các framework riêng để làm việc với database. Một số framework cung cấp các class, interface, attribute,… để lập trình viên sử dụng để tạo các entity. Điều này không xa lạ chút nào, và nó ảnh hưởng thế nào nếu đến lúc dự án cần thay đổi một framework mới? Bạn sẽ cần viết lại tất cả các lớp entity mặc dù database không thay đổi.

Rõ ràng rằng việc giữ cho các POCO đơn giản và độc lập khiến chúng trở nên linh hoạt và dễ dàng thay đổi. Bạn có thể thay đổi rất nhiều trong dự án, nhưng POCO vẫn không ảnh hưởng, và có thể được dùng trong nhiều dự án khác nhau. Theo đó, bạn có thể coi các POCO là một phần độc lập và hoàn toàn không phụ thuộc vào bất kì phần nào khác của dự án.

In this short tutorial, we'll investigate the definition of “Plain Old Java Object” or POJO for short.

We'll look at how a POJO compares to a JavaBean, and how turning our POJOs into JavaBeans can be helpful.

2. Plain Old Java Objects

2.1. What Is a POJO?

When we talk about a POJO, what we're describing is a straightforward type with no references to any particular frameworks. A POJO has no naming convention for our properties and methods.

Let's create a basic employee POJO. It'll have three properties; first name, last name, and start date:

public class EmployeePojo {

    public String firstName;
    public String lastName;
    private LocalDate startDate;

    public EmployeePojo[String firstName, String lastName, LocalDate startDate] {
        this.firstName = firstName;
        this.lastName = lastName;
        this.startDate = startDate;
    }

    public String name[] {
        return this.firstName + " " + this.lastName;
    }

    public LocalDate getStart[] {
        return this.startDate;
    }
}

This class can be used by any Java program as it's not tied to any framework.

But, we aren't following any real convention for constructing, accessing, or modifying the class's state.

This lack of convention causes two problems:

First, it increases the learning curve for coders trying to understand how to use it.

Second, it may limit a framework's ability to favor convention over configuration, understand how to use the class, and augment its functionality.

To explore this second point, let's work with EmployeePojo using reflection. Thus, we'll start to find some of its limitations.

2.2. Reflection with a POJO

Let's add the commons-beanutils dependency to our project:


    commons-beanutils
    commons-beanutils
    1.9.4

And now, let's inspect the properties of our POJO:

List propertyNames =
  PropertyUtils.getPropertyDescriptors[EmployeePojo.class].stream[]
    .map[PropertyDescriptor::getDisplayName]
    .collect[Collectors.toList[]];

If we were to print out propertyNames to the console, we'd only see:

[start]

Here, we see that we only get start as a property of the class. PropertyUtils failed to find the other two.

We'd see the same kind of outcome were we to use other libraries like Jackson to process EmployeePojo.

Ideally, we'd see all our properties: firstName, lastName, and startDate. And the good news is that many Java libraries support by default something called the JavaBean naming convention.

3. JavaBeans

3.1. What Is a JavaBean?

A JavaBean is still a POJO but introduces a strict set of rules around how we implement it:

  • Access levels – our properties are private and we expose getters and setters
  • Method names – our getters and setters follow the getX and setX convention [in the case of a boolean, isX can be used for a getter]
  • Default Constructor – a no-argument constructor must be present so an instance can be created without providing arguments, for example during deserialization
  • Serializable – implementing the Serializable interface allows us to store the state

3.2. EmployeePojo as a JavaBean

So, let's try converting EmployeePojo into a JavaBean:

public class EmployeeBean implements Serializable {

    private static final long serialVersionUID = -3760445487636086034L;
    private String firstName;
    private String lastName;
    private LocalDate startDate;

    public EmployeeBean[] {
    }

    public EmployeeBean[String firstName, String lastName, LocalDate startDate] {
        this.firstName = firstName;
        this.lastName = lastName;
        this.startDate = startDate;
    }

    public String getFirstName[] {
        return firstName;
    }

    public void setFirstName[String firstName] {
        this.firstName = firstName;
    }

    //  additional getters/setters

}

3.3. Reflection with a JavaBean

When we inspect our bean with reflection, now we get the full list of the properties:

[firstName, lastName, startDate]

4. Tradeoffs When Using JavaBeans

So, we've shown a way in which JavaBeans are helpful. Keep in mind that every design choice comes with tradeoffs.

When we use JavaBeans we should also be mindful of some potential disadvantages:

  • Mutability – our JavaBeans are mutable due to their setter methods – this could lead to concurrency or consistency issues
  • Boilerplate – we must introduce getters for all properties and setters for most, much of this might be unnecessary
  • Zero-argument Constructor – we often need arguments in our constructors to ensure the object gets instantiated in a valid state, but the JavaBean standard requires us to provide a zero-argument constructor

Given these tradeoffs, frameworks have also adapted to other bean conventions over the years.

5. Conclusion

In this tutorial, we compared POJOs with JavaBeans.

First, we learned a POJO is a Java object that is bound to no specific framework, and that a JavaBean is a special type of POJO with a strict set of conventions.

Then, we saw how some frameworks and libraries harness the JavaBean naming convention to discover a class's properties.

Chủ Đề