A while ago, with Java 10, a new controversial language feature was introduced: var. With var, local variables don’t need the explicit type information on the left-hand side anymore. Instead, it can be replaced with var like this:
In my experience as a passionate software craftsman, sometimes new language features aren’t adopted immediately for some reason or the other. Quickly, the moment to train a team of developers to use the new feature is gone, and the feature enters the “land of could use, but won’t use”, a.k.a “Locubwu”. So, highlighting a well-matured feature, I want to wrap up some guidelines, taken from the official OpenJDK article.
The reason number one to use var is to make code more readable. For example, when var is used to create a local variable in a method and its usages can be seen on only one screen, var can enhance the quick grasp of the method. Var is not meant to replace the full explicit variable declaration in all places. If the declaration of var cannot be understood just by looking at it and its vicinity, it should not be used.
That leads directly to the best practice of minimizing the scope of local variables. Instead of being used all over the place, a variable should have one well-defined purpose in a very confined code-space. So, var can support a clean code base if used properly.
With var, it is even more important to use descriptive names for your variables because the type of the variable is not visible immediately.
Chains of method calls can become tediously long in Java. var offers a nice way to smaller, more digestible parts of code by breaking the chain of method calls and extracting variables.
A nice side effect of using vars is the possibility to align variable names:
There are some more best practices and code snippets in the the official OpenJDK article, so make sure you’ll have a look at it. Because of the many years that have passed since the introduction in Java 10, there are many good articles about the topic like this one.