Weekend Reading List

Today is Thursday and every Thursday is #WeekendReadingList day. Today’s suggestions are:

Please send out your suggestions/reading list.

Happy learning!

Weekend Reading List

One of my goals to 2020 is to suggest every Thursday, a list of articles that we can read over the weekend. Our community produces a lot of content, and sometimes it’s hard to select what to consume. I hope this list can help us on our learning journey.

Today’s suggestions are:

Please send out your suggestions/reading list.

Happy learning!

Records – JEP 359

It’s frequently that when writing our code, we end up writing “data” classes(POJO). Classes with several properties, getters and setters, equals, hash code, toString and nothing else. Of course, all the code can be generated by the IDE and more recently Lombok but they are still required and are one of the reasons for Java be called “too verbose”.

Java over the past years has been presenting the community with several additions that aim to help the developer and create an easier and more inclusive environment. Better NullPointerException messages, JShell and more recently Records (a preview feature of Java 14) are a few examples.

Records (JEP 359) are a special type of class that holds immutable data. They are intended to be simple, eliminate boilerplate and will have generated automatically:

  • A private final field for each component of the state description;
  • A public read accessor method for each component of the state description, with the same name and type as the component;
  • A public constructor, whose signature is the same as the state description, which initializes each field from the corresponding argument;
  • Implementations of equals and hashCode that say two records are equal if they are of the same type and contain the same state; and
  • An implementation of toString that includes the string representation of all the record components, with their names.

Restrictions on Records

  • Can’t extend another class
  • Cannot declare instance fields other than the private final fields which correspond to components of the state description. All other fields MUST be static
  • They are final
  • Can’t be abstract

Declaring a Record

Before Java 14, if we want to create a POJO class with 2 properties (int age and String name), we would have at minimum the following code:

class Player {
    private int age;
    private String name;
    
    public Player(int age, String name) {
        this.age = age;
        this.name = name;
    }

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

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Player player = (Player) o;

        if (age != player.age) return false;
        return name != null ? name.equals(player.name) : player.name == null;
    }

    @Override
    public int hashCode() {
        int result = age;
        result = 31 * result + (name != null ? name.hashCode() : 0);
        return result;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

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

It’s a lot of code. But now let’s see the same code using Records:

record Player(int age, String name){}

Clean, simple and more readable.

I love this feature and believe it’s long overdue. IMHO, the community will quickly adopt it. What’s your opinion? Like, dislike?

Interview with a Java Champion – Edson Yanaga

Hello, Java community.

I’m starting a new blog series named Interview with a Java Developer. In the first episode, I had the honor to talk to Edson Yanaga (@yanaga). He’s the Director of Developer Experience at RedHat, Java Champion, Microsoft MVP among others.

Check the video below where we talk about technology, career and of course Quarkus. Hope you enjoy it.

 

Helpful NullPointerExceptions

JDK 14 will have a new feature, JEP 358 – Helpful NullPointerExceptions. This feature aims to bring a better understanding to the developer about the cause of a Null Pointer Exception.

Let’s take a look at the code below:

String name = student.getName();

The JVM would produce a message like:

Exception in thread "main" java.lang.NullPointerException at Student.main (Student.java:8)

That’s not bad. Lookin g at your code you can infer that “student” is null and that’s what caused the error. But consider this scenario:

String zipCode = student.getAddress().getZipCode();

That would trigger a similar error message. But now, where’s the error coming from? It is from “student” or “getAddress”?

Starting on JDK 14, the same error message would be:

Exception in thread "main" java.lang.NullPointerException:
  Cannot read field "zipCode" because "student.getAddress" is null 
  at Student.main (Student.java:8)

Much better IMHO.

What about you? What’re your thoughts?

Java 13 – Text Blocks

Java 13 adds a preview feature that supports JEP 355 – Text Blocks (previously JEP 326 – Raw String Literals). The goal is simple: make it easier to write String that span over several lines. This is especially useful when we are representing a SQL statement or a JSON.

Today, if we want to write a SQL statement it would look something like that:

String sql = "SELECT FIRST_NAME, LAST_NAME, AGE \n " +
             "FROM EMPLOYEE \n" +
             "WHERE AGE > 50";

The same query using Text Blocks can be written as:

String sql = """
             SELECT FIRST_NAME, LAST_NAME, AGE
             FROM EMPLOYEE
             WHERE AGE > 50
             """;

Much more readable right? Also, there’s no need to escape characters as single or double-quotes

Note the correct syntax. Three quotation marks(“””) to start the Text Block, followed by a mandatory new line where the code starts. Another three quotes set the end of the block.

String song = """
              The itsy bitsy spider climbed up the waterspout.
              Down came the rain
              and washed the spider out.""";
//okay
String song = """The itsy bitsy spider climbed up the waterspout.
Down came the rain
and washed the spider out.""";
//Illegal text block start. Missing new line after opening quotes

Note the behavior of text blocks.

String cities = """
                Paris
                New York
                Sao Paulo
                """;
//Is equivalent to "Paris\nNew York\nSaoPaulo\n"

If a line terminator is not required, then the closing delimiter can be placed on the last line of the content.

String cities = """
                Paris
                New York
                Sao Paulo""";
//Is equivalent to "Paris\nNew York\nSaoPaulo"

The position of the closing delimiter is important.

System.out.println("""
                    Hello World!
                    """);
//>Hello World!

System.out.println("""
    Hello World!
""");
//>    Hello World!

To support text blocks, new methods will be added to the String class

  • String::stripIndent(): used to strip away incidental white space from the text block content
  • String::translateEscapes(): used to translate escape sequences
  • String::formatted(Object... args): simplify value substitution in the text block

That’s a sneak peek at text blocks. Hope you enjoy it

Amazing members of Java community to follow on Twitter

That’s a small list of members of the community that I follow. All of them contributed to my growth and are a great source of knowledge (articles, tutorials, books and talks). They are very approachable and also have in common the passion for technology, the community and OSS.