Java's var keyword
If you’re working with Java, you would be aware of the var keyword which was introduced in Java 10 around 2018. The idea with var is that the compiler can often figure out the type, so you don’t need to declare it manually. For example…
var itemStats = createStats();
In this example, the signature from createStats() establishes the type for itemStats. Certainly there’s less text when using var, but I’m not sure the use of the var keyword leads to more readable code. The snippet below extrapolates on the single line above.
var hitSums = new HashMap<ItemIdentifier, Integer>();
var itemStats = createStats();
for (var id : itemStats.keySet()) {
var sum = itemStats.get(id).get("hits").stream().mapToInt(i -> i).sum();
hitSums.put(id, sum);
}
If the types are supplied explicitly in each case…
Map<ItemIdentifier, Integer> hitSums = new HashMap<ItemIdentifier, Integer>();
Map<ItemIdentifier, Map<String, List<Integer>>> itemStats = createStats();
for (ItemIdentifier id : itemStats.keySet()) {
int sum = itemStats.get(id).get("hits").stream().mapToInt(i -> i).sum();
hitSums.put(id, sum);
}
…then the result is much easier to follow. A snippet like this is often surfaced in a PR review and it’s really important that it can be easily followed.
I think if it’s not obvious what the type is, it’s better to provide it explicitly.