DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Java UDFs and Stored Procedures for Data Engineers: A Hands-On Guide
  • Using Java Class Extension Library for Data-Oriented Programming - Part 2
  • Using Java Class Extension Library for Data-Oriented Programming
  • Jakarta WebSocket Essentials: A Guide to Full-Duplex Communication in Java

Trending

  • AWS to Azure Migration: A Cloudy Journey of Challenges and Triumphs
  • How to Perform Custom Error Handling With ANTLR
  • Unlocking AI Coding Assistants: Generate Unit Tests
  • Agile’s Quarter-Century Crisis
  1. DZone
  2. Coding
  3. Java
  4. Java 21 Record and Pattern Matching: Master Data-Oriented Programming[Video]

Java 21 Record and Pattern Matching: Master Data-Oriented Programming[Video]

Java 21's JEP 440 introduces record patterns for data navigation, while JEP 441 brings pattern matching to switch statements, streamlining data-oriented programming.

By 
Otavio Santana user avatar
Otavio Santana
DZone Core CORE ·
Oct. 15, 23 · Analysis
Likes (2)
Comment
Save
Tweet
Share
9.3K Views

Join the DZone community and get the full member experience.

Join For Free

In the ever-evolving world of software development, data plays a central role. Handling and processing data efficiently is a paramount concern for developers. As one of the most widely used programming languages, Java acknowledges the significance of data-oriented programming with its latest enhancements in Java 21. Two significant Java Enhancement Proposals (JEPs) stand out: JEP 440 and JEP 441.

JEP 440: Record Patterns

JEP 440 is all about record patterns, a feature that significantly enhances the Java programming language’s capabilities regarding data manipulation. Record patterns introduce a new way of deconstructing record values, making data navigation and processing more declarative and composable.

Understanding Record Patterns

Consider a scenario with a user entity and two records: UserCreatedEvent and UserDeletedEvent. These records represent events that are associated with user activities.

Java
 
@Test
public void shouldGetEventDeleted(){
    User otaviojava = new User("otaviojava");
    Supplier<User> userSupplier = new UserDeletedEvent(otaviojava, Instant.now(), "nope reason");
    var log = log(userSupplier);
    Assertions.assertEquals(otaviojava, log.get());
}


In this example, the UserDeletedEvent record is created with specific attributes, including the user affected, the timestamp, and the reason for the event. Using record patterns, you can efficiently deconstruct the UserDeletedEvent and access its attributes without tedious if-else checks.

Deconstructing Records With Record Patterns

Let’s dive into the log method, which demonstrates the power of record patterns for data navigation:

Java
 
private Optional<User> log(Supplier<User> supplier){
    if(supplier instanceof UserCreatedEvent(User user, Instant instant) ){
        System.out.println("User created at " + instant + " with username " + user.username());
        return Optional of(user);
    } else if (supplier instanceof UserDeletedEvent(User user, Instant instant, String reason)) {
        System.out.println("User deleted at " + instant + " with username " + user.username() + " because " + reason);
        return Optional of(user);
    }
    return Optional.empty();
}


In this code, UserCreatedEvent(User user, Instant instant) and UserDeletedEvent(User user, Instant instant, String reason) are record patterns that allow you to directly access the user, instant, and reason attributes from the respective events. This approach is more concise and ensures that you work with data in a type-safe manner.

Reference:

JEP 441: Pattern Matching for Switch Expressions and Statements

While JEP 440 focuses on enhancing record patterns, JEP 441 extends pattern-matching capabilities by bringing it to switch expressions and statements. In this context, pattern matching enables concise and safe handling of complex data-oriented queries.

Pattern Matching With Switch Expressions

The fireEvent method demonstrates how pattern matching for switch expressions can be used effectively:

Java
 
String fireEvent(Supplier<User> supplier) {
    return switch (supplier){
        case UserCreatedEvent(var user, var instant) -> "User created at " + instant + " with username " + user.username();
        case UserDeletedEvent(var user, var instant, var reason) -> "User delete at " + instant +
                " with username " + user.username() + " because " + reason;
        default -> "No event";
    };
}


This code shows pattern matching in an switch expression. Each case in the switch expression specifies a pattern and a corresponding action. The patterns destructure the supplier object, allowing you to access the user event records’ attributes directly. This approach enhances the readability and maintainability of the code, making it easier to work with complex data structures.

Exploring Further

To delve deeper into the concepts and code samples discussed in this article, visit the GitHub repository at the following link: Java 21 Code Samples.

Embracing Data-Oriented Programming

With Java 21 and the introduction of JEPs 440 and 441, data-oriented programming in Java has reached a new level of sophistication. These features empower developers to work with data more effectively, enhancing code clarity, safety, and maintainability.

In a world where data is at the core of software development, mastering these data-oriented programming features in Java 21 is essential for staying at the forefront of the industry. Whether you are building applications that involve extensive data processing or simply striving for cleaner and more readable code, JEP 440 and JEP 441 are tools that every Java developer should add to their toolkit.

Embrace the power of record patterns and pattern matching in Java 21 to unlock the full potential of your Java applications. It’s a step towards more elegant and efficient data-oriented programming, making your codebase more robust and easier to manage. Java 21 sets the stage for a brighter and more data-centric future in Java development.



Data (computing) Java (programming language) Record (computer science) GitHub JDK Enhancement Proposal Java Data Objects Java Development Kit Language-oriented programming

Opinions expressed by DZone contributors are their own.

Related

  • Java UDFs and Stored Procedures for Data Engineers: A Hands-On Guide
  • Using Java Class Extension Library for Data-Oriented Programming - Part 2
  • Using Java Class Extension Library for Data-Oriented Programming
  • Jakarta WebSocket Essentials: A Guide to Full-Duplex Communication in Java

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!