Skip to main content

variables


Variables

This file will contain all the rules that needs to be followed related to variable declarations and usage standards.

var

Local variables are often initialized with constructors. The name of the class being constructed is often repeated as the explicit type on the left-hand side. If the type name is long, use of var provides concision without loss of information.

// traditional variable declaration in Java  
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

// variable declaration with type inference
var outputStream = new ByteArrayOutputStream();

It’s also reasonable to use var in cases where the initializer is a method call, such as a static factory method, instead of a constructor, and when its name contains enough type information:

// ORIGINAL
BufferedReader reader = Files.newBufferedReader(...);
List<String> stringList = List.of("a", "b", "c");

// GOOD
var reader = Files.newBufferedReader(...);
var stringList = List.of("a", "b", "c");

In these cases, the methods’ names strongly imply a particular return type, which is then used for inferring the type of the variable.

With var we don’t need to explicitly declare the type, it will be inferred by the compiler by looking at what was passed as the initializer in the declaration. That means we can’t set it as null because all non-primitive types can assume a null value, so there’s no way the compiler knows what type should be assigned to the variable. Another thing is that var works just like a short-hand for the traditional variable declaration, so once it is declared, we can’t assign a new value of a different type. Another technical detail, var is a reserved type name, not a keyword.

Pros

  • Less verbosity;
  • It encourages developers to write more descriptive variable names;

Cons

  • It makes the readability worse, specially outside the IDE, for example in GitHub;

Decision

Hence based on above suggestion (referred from Project Amber) its advised to use the var wherever possible.