To “var” or not to “var”, is that really the question?
A most common argument is that “var” should only be used together with LINQ. That makes no sense. Why is it acceptable to use with linq? Because it makes the code more readable than writing the complex type? You got it!
The fact is that the type isn’t that import anymore. Your business object probably got several representations today. You got your Entity Framework entity, your WCF service DTO, your ASP.NET MVC view model etc etc. That is, you have several representations of the same information which you work with. The actual type doesn’t really matter since it’s only valid in it’s own layer/class/scope. If you by mistake got another representation than your intended one, you’ll get feedback instantaneously from Visual Studio.
Is this code hard to read?
public ActionResult Create(UserViewModel model)
{
var user = _repository.Create(model.UserName);
user.LastName = model.LastName;
_repository.Save(user);
var admin = _user.Get(user.Id);
var email = _emailFactory.Create('RegistrationEmail');
email.SetTemplateTag('userName', user.UserName);
email.To = admin.Email;
smtpClient.Send(email);
return RedirectToAction('Index');
}
The fact is that the type is only important when you use crappy names:
User a = myObj.Get(1);
instead of
var admin = userRepository.Get(1);
As a developer you should always strive after writing as clean code as possible. Using var will shorten the code and therfore make it more readable. It will also move the focus from the types to what the code actually does.
Finally, here is my favorite motivation against “var”:
When I write code, not only do I think about performance and maintainability, I think about perhaps someday migrating it to another language. As such, I rarely use “var”.
Update
Many objects today are complex (i.e. not primitive or just having primitive properties). How do you treat them?
Do you type your code like this:
User user = _repos.Get(1);
Department department = user.Department;
_someService.Invoke(department);
instead of:
User user = _repos.Get(1);
_someService.Invoke(user.Department);
Of course not. Why not? Because given the context of the user, it’s obvious what the department type is. Same thing goes for when using your services, repositories and similar. If you load the user from a repository you know that it’s a db entity. No need to show the type.
Reference: To “var” or not to “var”, is that really the question? from our NCG partner Jonas Gauffin at the jgauffin’s coding den blog.