Tired of looking for errors in log files? Use OneTrueError - Automatic exception management for .NET.

To “var” or not to “var”, is that really the question?

There are several blog posts and discussions about whether to use var or not. They tend to focus on whether the type is obvious or not. It seems like people are afraid to suddenly be writing code in a dynamic language just because they can’t read the type anymore. I got news for you: You’ll still get a compiler error and an intellisense warning if you pass the wrong type to a method.

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”.

Cheers!

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.

This entry was posted in Architecture. Bookmark the permalink.
  • http://www.mfranc.com LaM

    I love the last quote haha.
    I am using var everywhere i can. It was never a problem for me and knowledge about type is overrated.

  • http://daniellang.net/ Daniel Lang

    Ok, so what type is “email” here (string or complex):

    var email = _emailFactory.Create(“RegistrationEmail”);

    • http://www.gauffin.org jgauffin

      You can’t just take an arbitrary line and ask about the type. Explain why the type matters in the context of my example?

      The code tells a story in which the types do not matter, just like each individual word in a book doesn’t mean anything.

      If you want to lookup a specific word in a book you’ll use a dictionary. You don’t get a footnote for every word. When developing you got a great tool: Your IDE. You can just hover over the variable in Visual Studio to get the type if required.

    • Woodsy

      If it’s a string the implication is it’s an email address. The solution there is to name your field properly i.e. “emailAddress”. This is greatest thing about ‘var’ in my opinion, it encourages descriptive naming, rather than a reliance on the type to tell you all about your variables.

  • Mike Vanderkley

    I am not going to wait for a compiler error. I want to read and correct it while my eyes are focused on it.
    I only use var while typing a batch of code and then quickly go over it with ALT + Enter [enter] and the type is added for me.
    Readability is king. var is just lazy. Including a type name is just as important as the variable name chosen. (love how my post seems like it was written in 2020. Between that format and US date format, no wonder the the rest of the world is on its toes reading dates)

    • http://www.gauffin.org jgauffin

      Why is the type important to know when reading the code? (since you mentioned readability as the primary goal).

      There is a reason to why newspapers/magazines uses columns instead of long lines. Shorter lines are easier to read.

      As for dates: ISO 8601 is the current standard specification for date and time formatting. It states that date and time values should be organized from the most to the least significant part. That is to start with the year and end with the day.

  • http://blueonionsoftware.com Mike Ward

    I like var way better. It let’s me concentrate on what the code does and not how it does it.

  • Jork

    Hello,

    I replaced the var’s with types (guessing it). Which piece of code is more readable???

    Regards,
    Jork

    public ActionResult Create(UserViewModel model)
    {
        User user = _repository.Create(model.UserName);
        user.LastName = model.LastName;
        _repository.Save(user);
     
        User admin = _user.Get(user.Id);
        Email email = _emailFactory.Create("RegistrationEmail");
        email.SetTemplateTag("userName", user.UserName);
        email.To = admin.Email;
        smtpClient.Send(email);
     
        return RedirectToAction("Index");
    }
    
    • http://www.gauffin.org jgauffin

      Thank you. It’s up to you readers to decide that.

      I just want you to think about what really matters when writing code. Is the type really so important when reading code? I’m using a typed language so that I know that I get type safety (i.e. compile errors and not runtime errors), not because I have to know the exact type all the time. It’s more important to understand the logic.

    • Fabricio

      Actually, comming from Pascal coding, I do separate the declaration from setting the variable (even if I combine initially, many times I make CodeRush do the split).

      But it’s the best code of this post in terms of reading, hands down.

  • http://antonkallenberg.com/ Anton Kallenberg

    Agree! The type is not as important as the naming convention. Visual studio, Resharper and the compiler will give us the type information when needed. Explaining types all over seems in my opinion to be a result of a bad naming convention. I will go with Mike Ward on this one, “var” helps us focus on the actual code.

    I like the way “var” is improving applications naming convention which make our code easier to understand and maintain. Unfortunately you can use “var” with a bad naming conventions too which that gives us the opposite of what I just described. Somewhere we need to draw a line between unprofessional and professional code and “var” is not solution for the unprofessional code problem.

  • Bob Armour

    Each to their own, I suppose, unless you work in an environment where code has to be shared amongst developers, and some kind of concensus is usually a good idea.

    Other than ‘var’ being shorter than a lot of type names, I don’t really see any benefit.

    ‘You can just hover over the variable in Visual Studio to get the type if required.’

    If you need to hover, then the readability of the code is questionable anyway.

    Just what problem is ‘var’ addressing – if we didn;t have it, would code be any more difficult to read, or would it be of a lower standard?

    Whilst I agree that crappy names are always a bad thing, ‘var’ is just another crappy name to me.

    • KChaloux

      Var addresses DRY principles, especially in situations like:

      Dictionary<User,Email> emailDict = new Dictionary<User, Email>();
      

      vs.

      var emailDict = new Dictionary<User, Email>(); 
      

      You know from reading the line that emailDict must be an instance of Dictionary. The type declaration is just extra cruft that distracts the eye from important information.

      Also, in situations where you’re using various interchangeable collections, var makes it a lot nicer to change that specific type declaration in just one place rather than both. It’s `rarely` necessary, but it helps eliminate `unnecessary` duplication of code.

      • KChaloux

        … Apparently this comments system strips out my < and > symbols. Just mentally insert whatever types into that Dictionary declaration you want.

        • KChaloux

          Or I guess the HTML codes work… Original line should’ve read:

          Dictionary<User, Email&;gt emailDict = new Dictionary<User, Email&;gt();

          vs

          var emailDict = new Dictionary<User, Email&;gt();

  • http://www.stev.org/ James

    var should be used less. Type is actually important. When code is separated into layers the type information is lost then you start passing the wrong types to the functions.

    I am still yet to come across an problem where var actually needs to be used.

    However take the following. Somebody does “var user”. Now does that contain a username or a userid? If it was typed you can tell even with the badly named variable since it would be an int or a string for example.

    • http://www.gauffin.org jgauffin

      If you start passing the wrong type you’ll probably not layered your application properly. If you call a repository you’ll know that you got the domain model. If you get a a user from your webservice you’ll know that the type is a DTO. Why do you have to see that type for that?

      “var” is of course not required anywhere. It’s just some sugar in our code ( = it makes our code taste better ;) )

      In your last remark, the problem is not that “var” is used, but the poor naming. In that case the code would benefit from proper naming more than showing the type.

    • Antijoe

      Somebody does var user. Now does that contain a username or a userid? If it was typed you can tell even with the badly named variable since it would be an int or a string for example.

      So suppose the user variable is a IMyDefiniteUserContent(of IUserPrincipal, string, IMyUserWrapper(of IUserPrincipal, string)). How does that help with readability and the “obvious knowledge” of what the type of its LastName property is?

      (sorry: I’m using VB-like syntax to make sure no chars are eaten by the comment system)

      • http://www.gauffin.org jgauffin

        np. I’ve reformatted your comment.

        Great point about the LastName. I’ve updated my blog post.

  • Jork

    I am thinking about this: var admin = _user.Get(user.Id);

    I think that admin is an User type. I read the line as: return a user with Id?

    • http://www.gauffin.org jgauffin

      yeah. my mistake. the admin id should have been configured and read from somewhere.

      Good catch!

  • André Andersen

    Can’t agree more, Jonas.

  • Pingback: Interesting .NET Links - August 23 , 2012 | TechBlog

  • ThatGuyThatIsABetterProgrammer

    Sorry man, encouraging this behavior is encouraging poor readability. I shouldn’t have to dredge to method definitions to figure out what my value type is. Var has usage but using it “just because” is a recipe for disaster.

    • http://www.gauffin.org jgauffin

      imho I do motivate quite clear why I use it? Can you give an example where var is a problem?