avatarUğur Taş

Summary

The website content discusses the three types of constructors in Java Record classes: canonical (all-args), compact, and custom constructors, detailing their syntax and use cases.

Abstract

Java Record classes introduce several constructor types, each serving a specific purpose. The canonical constructor is the traditional all-args constructor, allowing for data manipulation and validation but potentially leading to code repetition. The compact constructor simplifies the process by handling operations with fewer lines of code, although it does not permit direct field assignments. Custom constructors cater to specific business requirements, avoiding unnecessary parameters and enhancing code clarity. The article provides examples and explanations for each constructor type, emphasizing the benefits and limitations to help developers make informed decisions when working with Record classes in Java.

Opinions

  • Canonical constructors are well-known and provide full control over argument manipulation and validation but may lead to redundant code.
  • Compact constructors are praised for their brevity and ability to reduce unnecessary code, although they have limitations regarding field assignments.
  • Custom constructors are seen as a flexible solution to meet specific business logic requirements, improving the readability and maintainability of the code.
  • The author suggests that custom constructors should delegate to the canonical constructor for argument manipulation, highlighting a best practice for using record classes.
  • The article encourages reader engagement and feedback, indicating the author's commitment to community interaction and content improvement.
  • The author values knowledge sharing and encourages readers to follow their work on social media and explore related content on the Codimis platform.

Constructor Types of Java Record Classes

Photo by Call Me Fred on Unsplash

With Record class type, various terminologies are introduced to Java developers. Compact constructor is one of them, and well known all-args constructor or all fields constructor is called a canonical constructor. Aside from these two constructor types, there is another type called a custom constructor for record classes. In the following sections, I’ll describe them with examples.

If you don’t have a medium membership, you can use this link to reach the article without a paywall.

Canonical Constructor

Almost every developer knows the canonical constructor type. It is the all-args constructor. In my previous record class type blog posts, I have used the canonical constructor to show examples. You can check them too. Their links are at the end of this post.

By writing a canonical constructor, you can manipulate the args and set the fields as you wish. In the below example, we intended to trim the name argument and convert the email argument to lowercase.

public record UserRecord(String name, int age, String email) {

  public UserRecord(String name, int age, String email) {
    this.name = name.trim();
    this.age = age;
    this.email = email.toLowerCase(Locale.ROOT);
  }
}

Canonical constructors give us a chance to make validations and data manipulations for our record classes. However, it has its drawbacks. You need to repeat some parts of the code, even though you don’t change anything. The age field is an example of that. There is no change or any manipulation or normalization, but we should assign the age argument to the age field. But compact constructors save us from dealing with disadvantages of this kind.

Compact Constructor

A compact constructor can be seen as a no-args constructor. We cannot assign argument values to fields in this constructor type. However, we can handle validations or normalization. Code in the example below does the same operation that we had in the canonical constructor example with fewer lines of code.

public record UserRecord(String name, int age, String email) {

  public UserRecord {
    name = name.trim();
    email = email.toLowerCase(Locale.ROOT);
  }
}

But as I mentioned it is not possible to assign argument values to the field, hence data manipulation is handled and the result is assigned back to the argument. If you attempt to assign an argument to a field you will end up with a “cannot assign a value to final variable ‘field_name’” error message.

Custom Constructor

We can create custom constructors for our specific requirements. Let's continue with the previous example. We have a UserRecord record class. In our business case, we don’t need to know the email address of the user. So we can set the email field with a null or empty value. In that case, our code for instance creation will look like this:

var user = new UserRecord(" a ", 18, null);

But we can take care to avoid null parameter passing with a custom constructor.

public record UserRecord(String name, int age, String email) {

  public UserRecord(String name, int age) {
    this(name, age, null);
  }
}

With this new custom constructor, We can create a record instance without null parameter passing.

var user = new UserRecord(" a ", 18);

The most critical part of the custom constructor is that you cannot make assignments. Instead, the custom constructor should call the canonical constructor of the record class with the manipulated arguments or with their custom values such as null for our example.

👏 Thank You for Reading!

👨‍💼 I appreciate your time and hope you found this story insightful. If you enjoyed it, don’t forget to show your appreciation by clapping 👏 for the hard work!

📰 Keep the Knowledge Flowing by Sharing the Article!

✍ Feel free to share your feedback or opinions about the story. Your input helps me improve and create more valuable content for you.

✌ Stay Connected! 🚀 For more engaging articles, make sure to follow me on social media:

🔍 Explore More! 📖 Dive into a treasure trove of knowledge at Codimis. There’s always more to learn, and we’re here to help you on your journey of discovery.

Other record class-related posts 👇

Java
Record
Java Records
Constructor Function
Recommended from ReadMedium