When should you use `var` and when should you avoid it? How would you set team guidance?
answer
- Readability test: clearer or murkier for the reader?
- Use when initializer names the type / long generics / loops
- Avoid when RHS hides the type (opaque method calls, bare literals)
- Compensate with strong variable names
- OpenJDK style guidelines + IDE type hints
basics
~20 sUse var when the type is obvious from the right-hand side, like var user = new User();. Avoid it when the type is unclear, like var x = doSomething();, because the reader can no longer see what x is.
solid answer
~50 s`var` is a readability tool, so the test is whether it makes code *easier* to read. Good uses: the initializer names the type (`var list = new ArrayList<String>()`), long generic types that add noise, and loop variables. Avoid it when the right-hand side hides the type — method calls with non-obvious returns (`var result = service.fetch()`), bare literals where the exact type matters, or chained/stream expressions whose result type isn't apparent. Also avoid relying on the diamond fallback to `Object` and never let `var` obscure a primitive-vs-boxed or numeric-width distinction that matters. The official JDK style guidance (Stuart Marks's guidelines) says: prefer `var` where it improves clarity, use good variable names to compensate for the missing type, don't use it just to save keystrokes, and be cautious with literals and diamonds. Team conventions should codify these and rely on IDE type hints rather than banning `var` outright.
go deeper
Knows to use var when the type is obvious (var u = new User()) and to write the type explicitly when it isn't.
Can give concrete good/bad examples and explains that the variable name must carry meaning when the type is dropped.
References the readability-first principle and OpenJDK style guidelines, handles diamond/literal edge cases, and weighs IDE type hints.
Can author and justify a team-wide policy and linter rules, balancing consistency, the 'program to the interface' debate for locals, and reviewer cognitive load.
## `var` is about readability, not laziness `var` changes nothing about how the program runs — it only changes what a human reads. So the only sensible question is: *does this `var` make the code clearer or murkier for the next reader?* The type information has not vanished; it has just moved from the source into the reader's head (or their IDE). Whether that trade is worth it depends entirely on context. ## When `var` helps **1. The initializer already names the type:** ```java var user = new User(); // obviously a User var names = new ArrayList<String>(); // obviously ArrayList<String> ``` Writing the type twice adds nothing. **2. The explicit type is long and noisy:** ```java Map<String, List<Customer>> m = getCustomerMap(); var m = getCustomerMap(); // less noise — IF the name/method makes the type clear ``` **3. Loop variables and try-with-resources:** ```java for (var entry : map.entrySet()) { ... } try (var in = Files.newInputStream(path)) { ... } ``` ## When to avoid `var` **1. The type is not apparent from the right-hand side:** ```java var result = service.process(input); // process() returns... what? ``` The reader now has to chase the method signature. Prefer the explicit type, or rename the method/variable. **2. Literals where the exact type matters:** ```java var timeout = 30; // int or long? seconds or millis? ``` Explicit types (and good names) carry intent. **3. Diamond fallback / generics ambiguity:** never write `var x = new ArrayList<>()` (becomes `ArrayList<Object>`); always supply the type argument. **4. When it hides a boxing or numeric-width decision** that downstream code depends on. ## Compensate with good names The single most important rule: when you drop the type, **the variable name must carry more meaning**. `var x = repo.find(id)` is bad; `var customer = repo.find(id)` recovers most of the lost information. ## Official guidance and tooling The OpenJDK *Local-Variable Type Inference Style Guidelines* (commonly attributed to Stuart Marks) frame the principles: (1) reading code matters more than writing it; (2) code should be clear from local reasoning; (3) `var` is fine when it doesn't hurt readability; (4) use it to break up chained/nested expressions; (5) don't worry about 'programming to the interface' for locals; (6) take care with diamonds and literals. Modern IDEs render an inline *type hint* next to a `var`, which removes most of the at-a-glance cost — a reason to lean toward allowing `var` rather than banning it. ## Setting team guidance A pragmatic policy: *allow `var` where the initializer makes the type obvious; require explicit types when the right-hand side is a non-obvious method call; always supply explicit type arguments (no bare diamond); pair every `var` with a descriptive name.* Encode it in the style guide and a linter rule rather than a blanket ban or blanket mandate.
- Someone argues `var` violates 'program to the interface' because it infers the concrete class. Is that a real concern for local variables?Largely no. 'Program to the interface' matters for API surface (fields, params, return types) where `var` is not even allowed. For a method-local variable the concrete type is an implementation detail with no external impact, so the official guidelines say not to worry about it for locals.
saying these in an interview costs you the question
- Treating `var` as just keystroke-saving rather than a readability decision
- Using `var x = someMethod()` where the return type is non-obvious
- Banning or mandating `var` everywhere instead of context-based guidance
- Leaving a bare diamond (`new ArrayList<>()`) and accepting `Object`