Java 11 best practices

Hello all,

We have adopted java 11 since the beginning of the 14.x cycle. On thing that haven’t been discussed is the best practices regarding the use of new features introduced in java 9, 10, and 11.

Most of the changes are at the JVM level, or are part of the Java API.

I think we can agree that new Java API can be used at will, except for code that have high chances to be back-ported to older branches.

One syntactic change has also been introduced in Java 10, LocalVariable Type-Inference (a.k.a., the var keyword), and that what I’d like to discuss.

In summary, using the var keyword let the compiler decide the actual static type of a variable from the context.
Note that this can only be used for local variables and, since java 11, for lambas parameters (and not for methods parameters or fields declaration for instance).

Some examples:

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

class DemoVar
{
    public static void main(String[] args)
    {
        var a = 1; // int
        var b = a + 1.0; // double
        var c = "Hello"; // String
        var mam = Map.of("a", 1, "b", 2); // Map<String, Integer>
        var list = List.of(1, 2.0, 11d); // List<Number & Comparable<? extends Number & Comparable<_>>>
        var list2 = new ArrayList<>(); // ArrayList<Object>
        var list3 = new ArrayList<String>(); // ArrayList<String>
    }
}

For the pros and cons, I’d like to quote OpenJDK Style guidelines:

There is a certain amount of controversy over this feature. Some welcome the concision it enables; others fear that it deprives readers of important type information, impairing readability. And both groups are right. It can make code more readable by eliminating redundant information, and it can also make code less readable by eliding useful information. Another group worries that it will be overused, resulting in more bad Java code being written. This is also true, but it’s also likely to result in more good Java code being written. Like all features, it must be used with judgment. There’s no blanket rule for when it should and shouldn’t be used.

So the questions is, do you agree to allow the use of the var keyword on 14.x+.
If we go for yes, I suggest to do so only while following the style guidelines of openjdk.

WDYT?

Footnote:

Thanks for bringing this up

I’m not against using it in very specific cases such as loops (cf example given on Local Variable Type Inference: Style Guidelines)
Now I’m -1 to start using it on 14.x: we’re still supporting 13.x and it makes the backward compatibility to LTS more difficult. So I’d be +0 for allowing it on 15.x.