I personally use var quite often, but with few rules.
Use, when variable name is good enough to tell the full story - which should always be the case, but we arent perfect.
Don't use when ą type can't be determined by scanning the block it is in, which practically means that i avoid using it to assign the result of a method, unless it is obvious what the return type is.
Don't use when dealing with generics, eg Map, Collection, etc.
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.
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)).
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.
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.
2
u/bezik7124 Sep 16 '20 edited Sep 18 '20
I personally use var quite often, but with few rules.
Use, when variable name is good enough to tell the full story - which should always be the case, but we arent perfect.
Don't use when ą type can't be determined by scanning the block it is in, which practically means that i avoid using it to assign the result of a method, unless it is obvious what the return type is.
Don't use when dealing with generics, eg Map, Collection, etc.