5

Unfortunately, there is no item in Effective Java that discusses the reserved type name "var"(since it is introduced in java 10).

There is a saying to use interfaces as types whenever you can (Item 64: Refer to objects by their interfaces). But When using var:

var list = new ArrayList<String>(); // infers ArrayList<String>

(list is of type ArrayList<String>)

Effective Java states It is a bad practice to refer to a variable by its implementation because It makes code dependent on it. This is just one annoyance I've found when starting to use var in my code.

Question:

Are there any best practices when using the reserved type name "var"? When should I use It? When should I avoid it?

Hamza Belmellouki
  • 2,516
  • 1
  • 18
  • 39
  • 9
    Read the [guidelines here](http://openjdk.java.net/projects/amber/LVTIstyle.html) – Naman Oct 01 '19 at 10:54
  • [Here](https://www.baeldung.com/java-10-local-variable-type-inference) is another blog for clearing up the basics. – Sri9911 Oct 01 '19 at 11:24
  • You can check also the official Java doc related to java10 (Local-Variable Type Inference) support https://docs.oracle.com/javase/10/language/toc.htm – Ahmed Nabil Sep 28 '22 at 07:37

0 Answers0