I just watched an excellent presentation by Jimmy Bogard on UI testing with ASP.NET MVC. While I really enjoyed the presentation and got a lot of really good ideas for how to improve how I work with MVC, I saw something that I really did not like: lots of var keywords. Here’s an example (recreated from memory so it might not be exactly right) of one of the methods he showed during his presentation:
... var id = UINameHelper.GetName(expression); var func = expression.Compile(); var value = func(model); ...
What’s wrong with that code? Well, unless I know the API, which I don’t, I don’t know the types of the variables. I can make certain assumptions about their types (the first is probably a string, the next is presumably a Func<T1,T2>, the third I’m not sure about), but I don’t know for sure unless I inspect the code further. Sure, intellisense is going to help, but I don’t have intellisense when I’m watching a presentation or looking at a code sample over someone’s shoulder. I have the code, and that’s it. The code should be readable without an IDE. It should be just as clear when I’m using Notepad++ or looking at it on your blog as when I’m digging through it with VS.NET.
There are times when the var keyword can make code more readable. A great example is when working with complex generics:
//Less readable Dictionary<int,Pair<Foo,Bar>> lookup = new Dictionary<int,Pair<Foo,Bar>>(); //More readable var lookup = new Dictionary<int,Pair<Foo,Bar>>();
So, a request to all my fellow developers out there: please use the var keyword carefully. I don’t think it should ever be used when assigning a variable to a method’s return value. I think it should only be used when it actually *improves* readability of the code, and never when it takes away from it.
Thoughts? Is var the best thing since sliced bread or the worst thing since IE6? When do you think it’s ok to use var?