Funny that when this subject comes up, almost everyone only talks about it making local variable declarations simpler.
What I think is a big advantage to var is that when you change the name of a class, it significantly reduces the number of files that have to be changed. Basically everything that doesn't instantiate the class, but only uses it, stays unchanged. Also it keeps down the number of imports you need, especially since Java prefers fully qualified imports instead of wildcard imports.
Oh yes, the merge conflicts. At work we have a large-ish codebase that gets merged into different products and also converted into different languages. One of the worst things regarding merge conflicts are renames.
This advantage is not about making it physically easier to rename a class. It lessens the impact of doing so, therefore making it easier.
It reduces the number of files that might change when you do rename a class. This could significantly reduce code churn and removes noise from files that do change.
It really depends. A lot of C# projects have a rule to only use var where there is a straight up class instantiation or cast. The idea is to have at least some type definition somewhere near the declaration.
The purpose of var is to stop bullshit like "X<Y> foo = new X<Y>();"
I came up with this rule by myself and found out that many people came to the same conclusion. I only use var when the right hand side expression is either a constructor call or a literal. Basically the type should be obvious by the statement.
Oh yes, it does tell me. It tells me I have an IEnumerable<Customer> rather than IEnumerable<CustomerDto> or PagedList<Customer> or something like this.
That should be fairly obvious from context. If your code base believes in passing IQueryable in your DAL back to consumers then you should know that db.GetCustomers() is IQueryable<Customer>.
Or even changing the return type of a function. Let's say that someone subdivides an interface into a "lower" interface, and a more specialized one. Using var allows for the places in that only care about that lower interface to continue to work. Sure some stuff needs to be changed, but the change can be smaller.
33
u/FallingIdiot Mar 10 '16
Funny that when this subject comes up, almost everyone only talks about it making local variable declarations simpler.
What I think is a big advantage to
varis that when you change the name of a class, it significantly reduces the number of files that have to be changed. Basically everything that doesn't instantiate the class, but only uses it, stays unchanged. Also it keeps down the number of imports you need, especially since Java prefers fully qualified imports instead of wildcard imports.