What are best practices for working with var (local variable type inference)?

When working with the var keyword in Java, which allows for local variable type inference, it's essential to adhere to best practices to maintain code readability and robustness. Here are some best practices:

  • Use for Local Variables: Prefer using var for local variables where the type is obvious from the context. This improves readability.
  • Avoid in Complex Declarations: Avoid using var for complex types or expressions that can confuse readers regarding the actual type.
  • Type Consistency: Ensure that the inferred type is consistent and predictable. Avoid scenarios where the type might change in a loop or conditional code.
  • Maintain Code Clarity: If it reduces clarity, prefer explicitly declaring the type instead of inferring it with var.
  • Upgrade Awareness: Be aware that var cannot be used for class fields, method parameters, or return types. Use it judiciously within method bodies.

Here’s an example of using var for local variable type inference:

var numberList = new ArrayList(); for (var number : numbers) { System.out.println(number); } var sum = numberList.stream().mapToInt(Integer::intValue).sum();

var local variable type inference Java best practices code readability coding standards