Backstory

The other day at work, I had a coworker look over some changes I made to one of our Java applications. He gave me some pretty standard feedback: this looks good, fix this, etc. But he also told me that I really shouldn’t be using var for my variable assignments because it “makes the code less readable”. I put a lot of effort in trying to make my code as readable as possible so his comment took me back for a moment. Have I been littering the code I write with this garbage that makes difficult to understand just to use some newfangled language syntax? So I took a few moments to try and understand why he thinks this.

Java type inference

Back in 2018 Oracle released Java 10 with a bunch of fancy new features. One of these features was the introduction of type inference though the use of the var identifier which can really simplify the way your code looks by stripping out a lot of unnecessary information. Take this code for example:

public class MyClass {
    public MyClass() {
        Map<String, String> myMap = new HashMap<>();
        myMap.put("some-key", "some-value");

        for (Map.Entry<String, String> i : myMap.entrySet()) {
            System.out.println(i);
        }
    }
}

The syntax for the loop is super verbose. You already know what the type of myMap is, so why clutter things with typing info? Here’s that same code using type inference:

public class MyClass {
    public MyClass() {
        Map<String, String> myMap = new HashMap<>();
        myMap.put("some-key", "some-value");

        for (var i : myMap.entrySet()) {
            System.out.println(i);
        }
    }
}

That looks much cleaner, and it’s easier to read. Granted this is just a meaningless few lines of code but that reduction of redundant typing info will add up quick in large codebase.

Of course though, you don’t want to use var if it’s going to make your code more difficult to read or put you in a situation to (probably) make dangerous typing assumptions.

Differing opinions

I’m glad I took the time to try and better understand why my coworker has the blanket opinion that using Java’s var makes code less readable, but I still completely disagree. Maybe he doesn’t understand Java’s typing system very well, maybe he just doesn’t like change, or maybe I’m still missing something? Java is a statically typed language with strong typing so the use of type inference is usually a good thing. That’s what I still think at least. As with basically everything else in programming, type inference can make your code easier to read when used properly.