Saturday, April 11, 2020

Java 14 - New Features - Part 1


JDK 14 was released on March 2020.

With new programming languages and frameworks that pop up like mushrooms after the rain we can see a movement moving towards writing a code will be less tiring and less verbose with a lot more meanings. we can see from COBOL language that first appeared in 1959 that is verbose, uses over 300 reserved words and have statements that is English-like syntax where we heading to. 

Some can say that Java is too verbose and tedious, let's take a simple class for example - Pet class, so you have the name of the class and now you need to implement it, so you may need constructor, equals(), hashcode(), accessors, toString(), etc. So i know that you have an IDE that can generate it for you.


public class Pet {
    private String name;
    private Person owner;

    public Pet(String name, Person owner) {
        this.name = name;
        this.owner = owner;
    }

    @Override    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Pet pet = (Pet) o;
        return Objects.equals(name, pet.name) &&
                Objects.equals(owner, pet.owner);
    }

    @Override    public int hashCode() {
        return Objects.hash(name, owner);
    }

    @Override    public String toString() {
        return "Pet{" +
                "name='" + name + '\'' +
                ", owner=" + owner +
                '}';
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Person getOwner() {
        return owner;
    }

    public void setOwner(Person owner) {
        this.owner = owner;
    }
}


In recent years, JAVA architects and developers have taken steps to make the code less "ceremony", less tedious, less tiring and easier to code.

In this article i will talk about several new features that took place in Java 14.


Text Blocks (Second Preview)


This is a preview language feature in JDK 14.

Imagine you need to write an SQL query, you go to your database design tool, let's say workbench and think, implement and test your query, after doing so you need to copy & past it to your java project (if your application use plain text SQL), And this is where the problem begins. You are not sure about the indentation, you struggle a lot with the quotation marks in each line - it's so annoying.

This is where Text Blocks come to the rescue. Text Blocks introduced in early 2019 and now we can find it in JDK 14 as second Preview with two new escape sequence, \s and \ .
The goals is to simplify, make it easy to express strings that span in several lines and enhance the readability of strings.

Before Text Blocks

"INSERT INTO users " +
"  ( " +
"     first_name " +
"     ,last_name " +
"     ,email " +
"  ) " +
"VALUES " +
"  (  " +
"     :first_name " +
"     ,:last_name " +
"     ,:email " +
"  )  ";

With Text Blocks

"""        
INSERT INTO 
   users 
   ( 
      first_name 
      ,last_name 
      ,email 
   ) 
VALUES 
   (  
      :first_name 
      ,:last_name 
      ,:email 
   )  
""";

surround the string with 3 quotation marks.

\s - this escape can be used for single space and this  escape can be used for newline that its usable for readable texts.

It's not just very helpful for SQL queries string, also helpful for HTML, XML, JSON and every string that usually requires significant editing with escapes and concatenation.

Regarding the compile-time processing - the content is processed by the java compiler in three steps: line termination; incidental white space surrounding the content, is removed; Escape sequences in the content are interpreted.

At run-time, a text block is evaluated to an instance of String, just like a string literal.



Pattern Matching for instanceof (Preview)


This is a preview language feature in JDK 14.

The goal is to extract more from pattern matching for the instanceof operator.

The logic of the following code is to testing if an expression has a certain type or structure, and then conditionally extracting components of its state for further processing.

if (obj instanceof Integer) {
    int num = ((Integer) obj).intValue();
    // use num
}


This part of code is commonly in use and it is tedious. Let's understand what we see here
  1. Test if obj a Integer.
  2. Casting obj to Integer.
  3. Declaration of new local variable - num.

Imagine you can do the 3 above in 1, now with Pattern Matching for instanceof, you can:

if (obj instanceof Integer num) {
    // use num here (num is binding to this block)
} else {
    // can't use num here.
 }

It gives the ability to use easier syntax to extract components of objects.



We are seeing efforts towards easier coding in Java, that trying to keep up with other languages.




No comments:

Post a Comment

JVM Crashes

Case Study - I gonna write a true story that happened on a company which I work for. I got a task: Crash Hunting Me: Who Crash? QA: Th...