javavarlombokjava-10

Use cases when Lombok or Java 'var' is useful


var is not very handful when you're navigating through the code and investigating the code which is not clear at the first look.

When developers use not self-describing methods names you have to spend some time to understand what is real type of the variable. And if you use Lombok's var you will be tightly coupled with Lombok, so I do not use it very often in my code.

What are the useful use cases for using var in Java?


Solution

  • Arguments in favor of var:

    Arguments against var:

    Most of these are taken from this post for when to use var in .NET C#, where the var keyword has been present since the beginning, whereas with Java it's only available since version 10.

    Oh, and another big advantage of var: it's shorter for code-golfing (creating a program/function which does a certain task/challenge with as few bytes as possible). :) Probably the main reason why I don't mind that it was added, since I codegolf in Java (as well as .NET C#, 05AB1E, and Whitespace) pretty often.

    Related: Java 7's diamond operator. List<String> names = new ArrayList<>(); vs List<String> names = new ArrayList<String>();.

    Personally I still use written out types instead of var, except for code-golfing. But maybe I just need to get used to it a bit more before using it more often. For readability, and making it clearer and easier to see the type without having to dig, I don't use var at all. As for Java 7's diamond operator, I only use it when I instantiate it directly after the field, but would not when I instantiate it elsewhere (i.e. I would use List<String> names = new ArrayList<>();, but not List<String> names; /* ... some code here ...*/ names = new ArrayList<>();).
    In general it all comes down to preference, though.