r/programming • • Sep 15 '20

Java 15 released!

https://jdk.java.net/15/
214 Upvotes

130 comments sorted by

View all comments

Show parent comments

1

u/eeperson Sep 16 '20

Don't use when dealing with generics, eg Map, Collection, etc

I actually feel that this is one of the better places to use var. I find that people tend to shy away from more complex types to fully express constraints. With var you can propagate more complex types without having to write it over and over.

1

u/bezik7124 Sep 17 '20

tl;dr readability > having to write less code

I don't mind writing longer declarations over and over, modern IDE's doing it for me anyway. I use var not to make writing the code easier, but to make reading the code easier.

And sometimes having the type is just a noise (eg UUID uuid = UUID.randomUUID()), while other times it can be really helpful to look at the type when reading stuff (eg Multimap<Invoice, OrderPosition> invoiceToOrderPositions = fetchOrderPositionsGroupedByInvoiceByDateRange(rangeStart, rangeEnd)).

4

u/eeperson Sep 18 '20

Multimap<Invoice, OrderPosition> invoiceToOrderPositions = fetchOrderPositionsGroupedByInvoiceByDateRange(rangeStart, rangeEnd)

I think we have slightly different opinions about readability. I actually think is an even better place to use a var. I feel like the type is implied by both the variable name and the function being called. So, just like in your first example, I feel like the type declaration is redundant. However, I feel like it is even worse on this line because the type declaration is fairly long and the line is already long. So, I feel like the type declaration makes this line much harder to parse visually.

1

u/bezik7124 Sep 18 '20

It is a bit too long, true. Perhaps i've came up with a bad example, because i wanted to shine now and ask you how would you distinguish whether the type is a Multimap or Map of Collections, but tbh who cares? It's used the same way.

I can now agree that my rule no. 2 was wrong, if someone still can't deduce the type on the fly, then probably variable name is at fault.