Coffeehouse Thread

14 posts

Forum Read Only

This forum has been made read only by the site admins. No new threads or comments can be added.

Do you use the "var" keyword/alias liberally

Back to Forum: Coffeehouse
  • User profile image
    vesuvius

    In .NET 3.0 (and .NET 2.0 SP1) the var keyword was introduced to assist type inference situations. While I can see the benefits of it when using the

    var query = from x in y
                           where x = "London"
                            select x

    I don't think you should use it "just because you can". It is very easy to use, but if you are reading someone else's code, there is an moment where you have to look at the declaration and decipher what var is, whereby if the person who wrote the code had not been lazy and written (to take PerfectPhase's example)

    MessageQueue mqRx = new MessageQueue(@"FormatName:DIRECT=OS:localhost\private$\inputmessages", false, false, QueueAccessMode.Receive);

     In Visual basic, there is no new var type keyword (I find this consistent) and Dim remains i.e.

    Dim numberOfStudents As Integer, to declare an integer

    where the Linq query would be (though I hate the underscore)

    Dim OrdersShippedToWA = From Ord In Orders _
                            Where Ord.Shipped _
                                And Ord.State = "Washington" _
                                    Select Ord.ID, OrderDate = Ord.Date, _
                                    Ord.Address, Ord.City, _
                                    Ord.State, Ord.Zip


    I just think this results in your code being less readable, for no tangible benefit. What do you think?

  • User profile image
    Dr Herbie

    I've recently started using var, but only in unit testing when creating a mock class.
    I consider Unit Tests to be 'throwaway code' in that they get rewritten several times as I refine my domain models, so using var is a convenient shorthand.

    Herbie

  • User profile image
    Sven Groot

    Type inference has its uses. It's pretty much required for Linq because you just don't want to spend an hour figuring out just what your query is going to return (not to mention if you use anonymous types you can't even explicitly type the result).

    In C# there is the marginal benefit of being able to avoid the repeated types in something like this:
    System.Collections.Generic.Dictionary<string, Foo> someVar = new System.Collections.Generic.Dictionary<string, Foo>();

    That's only a small thing though if you're using VS because you don't actually have to type the second occurrence. VB does this better with the "Dim someVar As New Whatever()" construct that has existed since the old days (although prior to VB.Net 2002, the semantics were different; it was a lazy initialization in old VB).

    The third thing where I think it's useful (and I really use it a lot here) is in foreach loops. It's just nice being able to say "foreach( var item in list )" without having to worry about the exact type in the list, even more so if you're using a dictionary where the enumerated type is a KeyValuePair<TKey, TValue> which I can never remember.

  • User profile image
    Ion Todirel

    Dr Herbie said:
    I've recently started using var, but only in unit testing when creating a mock class.
    I consider Unit Tests to be 'throwaway code' in that they get rewritten several times as I refine my domain models, so using var is a convenient shorthand.

    Herbie
    yes if the type definition is long enough to activate "laziness  mode", for short type definitions like "int, string... " almost never, only if the method is containing x type definitions from which at least one is long enough to use "laziness mode":

    bool isIE = _owner.Page.Request.Browser.MSDomVersion.Major > 0;
    int depth = 0;

    var nodes = new Queue<TreeNode>(this.Nodes);
    var index = 0;

  • User profile image
    Ion Todirel

    Sven Groot said:
    Type inference has its uses. It's pretty much required for Linq because you just don't want to spend an hour figuring out just what your query is going to return (not to mention if you use anonymous types you can't even explicitly type the result).

    In C# there is the marginal benefit of being able to avoid the repeated types in something like this:
    System.Collections.Generic.Dictionary<string, Foo> someVar = new System.Collections.Generic.Dictionary<string, Foo>();

    That's only a small thing though if you're using VS because you don't actually have to type the second occurrence. VB does this better with the "Dim someVar As New Whatever()" construct that has existed since the old days (although prior to VB.Net 2002, the semantics were different; it was a lazy initialization in old VB).

    The third thing where I think it's useful (and I really use it a lot here) is in foreach loops. It's just nice being able to say "foreach( var item in list )" without having to worry about the exact type in the list, even more so if you're using a dictionary where the enumerated type is a KeyValuePair<TKey, TValue> which I can never remember.
    +1 for for/foreach loops + if you write a lot of JavaScript is easier to change the context

  • User profile image
    stevo_

    Ion Todirel said:
    Dr Herbie said:
    *snip*
    yes if the type definition is long enough to activate "laziness  mode", for short type definitions like "int, string... " almost never, only if the method is containing x type definitions from which at least one is long enough to use "laziness mode":

    bool isIE = _owner.Page.Request.Browser.MSDomVersion.Major > 0;
    int depth = 0;

    var nodes = new Queue<TreeNode>(this.Nodes);
    var index = 0;
    I use it anywhere where the right hand side describes the 'situation' enough.. I tend to find that good design of code the right hand side becomes somewhat self descriptive anyway, so the var keyword then can be used quite often..

    I still do int i = 0 in for loops for example though.. but only really because I think it stays consistent with what people expect..

  • User profile image
    vesuvius

    Sven Groot said:
    Type inference has its uses. It's pretty much required for Linq because you just don't want to spend an hour figuring out just what your query is going to return (not to mention if you use anonymous types you can't even explicitly type the result).

    In C# there is the marginal benefit of being able to avoid the repeated types in something like this:
    System.Collections.Generic.Dictionary<string, Foo> someVar = new System.Collections.Generic.Dictionary<string, Foo>();

    That's only a small thing though if you're using VS because you don't actually have to type the second occurrence. VB does this better with the "Dim someVar As New Whatever()" construct that has existed since the old days (although prior to VB.Net 2002, the semantics were different; it was a lazy initialization in old VB).

    The third thing where I think it's useful (and I really use it a lot here) is in foreach loops. It's just nice being able to say "foreach( var item in list )" without having to worry about the exact type in the list, even more so if you're using a dictionary where the enumerated type is a KeyValuePair<TKey, TValue> which I can never remember.
    I never thought I'd see the day where I liked Visual Basic, but in some respects it is far easier  and more sensible than C type languages, where the focus is on being as "terse" as possible maintaining readability, VB can also be terse, and very readable - anyway enough of that.

    Is there absolutely no difference in using "var" in a foreach loop with a Generic Dictionary instead of KeyValuePair<key, value>? Surely you're giving the compiler that much more work to infer the KeyValuePair where if you used the generic syntax it's less work in the loop, hence better performing speed wise?

  • User profile image
    foreachdev

    stevo_ said:
    Ion Todirel said:
    *snip*
    I use it anywhere where the right hand side describes the 'situation' enough.. I tend to find that good design of code the right hand side becomes somewhat self descriptive anyway, so the var keyword then can be used quite often..

    I still do int i = 0 in for loops for example though.. but only really because I think it stays consistent with what people expect..
    I disagree. I mostly use it for long namespaces. My current project likes to name things like so:
    Company.Project.Business.Logic.Exception
    Company.Project.Business.Application.Logic.Module.SubModule

    When newing up objects of that type via a factory method or even via new constructor its good to not have to figure out what long winded namespace they live in. Knowing it really adds nothing to the programming experience.

    And why not use var in those cases? Its a convienence.

  • User profile image
    Sven Groot

    vesuvius said:
    Sven Groot said:
    *snip*
    I never thought I'd see the day where I liked Visual Basic, but in some respects it is far easier  and more sensible than C type languages, where the focus is on being as "terse" as possible maintaining readability, VB can also be terse, and very readable - anyway enough of that.

    Is there absolutely no difference in using "var" in a foreach loop with a Generic Dictionary instead of KeyValuePair<key, value>? Surely you're giving the compiler that much more work to infer the KeyValuePair where if you used the generic syntax it's less work in the loop, hence better performing speed wise?
    But the work is done at compile time (and by the C# compiler, not the JIT compiler). There is no difference at runtime, just the compilation might take 1ms longer.

    That's the big difference between dynamic types and type inference. These objects are not late bound. All the work is done by the compiler, nothing changes while the app is running compared to when you explicitly declared the type.

    EDIT: That's also why you can use this feature in VS2008 even when you're targeting .Net 2.0, because there's nothing the CLR needs to do at runtime, the generic IL code is the same as with an explicit declaration.

  • User profile image
    stevo_

    foreachdev said:
    stevo_ said:
    *snip*
    I disagree. I mostly use it for long namespaces. My current project likes to name things like so:
    Company.Project.Business.Logic.Exception
    Company.Project.Business.Application.Logic.Module.SubModule

    When newing up objects of that type via a factory method or even via new constructor its good to not have to figure out what long winded namespace they live in. Knowing it really adds nothing to the programming experience.

    And why not use var in those cases? Its a convienence.
    You disagree with what? also namespaces have nothing to do with this considering:

    using statements.
    var doesn't make the right hand side any smaller so you would still need to write:

    var car = new Super.Long.And.Really.Should.Just.Use.A.Using.Statement.Class();

  • User profile image
    vesuvius

    foreachdev said:
    stevo_ said:
    *snip*
    I disagree. I mostly use it for long namespaces. My current project likes to name things like so:
    Company.Project.Business.Logic.Exception
    Company.Project.Business.Application.Logic.Module.SubModule

    When newing up objects of that type via a factory method or even via new constructor its good to not have to figure out what long winded namespace they live in. Knowing it really adds nothing to the programming experience.

    And why not use var in those cases? Its a convienence.
    Yes you are right, that is your convenience but think of the person who will read your code in 3 years time.

    " its good to not have to figure out what long winded namespace they live in"


    This epitomises why using var as little as possible is a good thing. As a developer you are tasked with creating libraries, for the really long ones the using keyword greatly simplifies things. It is so important that someone looking at your code can anticipate why x works with y, and your "convenience" makes things that much harder. A good program should read like a book, without resorting to annotation.

    If you read a historic book, lets say "War and Peace" by Leo Tolstoy, you have the annotation at the bottom saying, the political environment was like this, and the serfs were about to launch a revolt. This is all relevant and important. With your method, it means having to resort to intellisense and it makes for a stuttered way of deducing the code that's written and that much harder.

    This, as they say on the internets, is "My 2 Cents".

  • User profile image
    PerfectPhase

    vesuvius said:
    foreachdev said:
    *snip*
    Yes you are right, that is your convenience but think of the person who will read your code in 3 years time.

    " its good to not have to figure out what long winded namespace they live in"


    This epitomises why using var as little as possible is a good thing. As a developer you are tasked with creating libraries, for the really long ones the using keyword greatly simplifies things. It is so important that someone looking at your code can anticipate why x works with y, and your "convenience" makes things that much harder. A good program should read like a book, without resorting to annotation.

    If you read a historic book, lets say "War and Peace" by Leo Tolstoy, you have the annotation at the bottom saying, the political environment was like this, and the serfs were about to launch a revolt. This is all relevant and important. With your method, it means having to resort to intellisense and it makes for a stuttered way of deducing the code that's written and that much harder.

    This, as they say on the internets, is "My 2 Cents".

    I just went back and had a look at some of the code i've written over the last week, the only places I had even had a moment's doubt about what the var meant was the result of the LINQ queries and they are pretty much the only ones I can't do anything about Smiley


  • User profile image
    JChung2006

    var is required for anonymous types.  Otherwise, it's a tradeoff between readability and conciseness.

  • User profile image
    androidi

    PerfectPhase said:
    vesuvius said:
    *snip*

    I just went back and had a look at some of the code i've written over the last week, the only places I had even had a moment's doubt about what the var meant was the result of the LINQ queries and they are pretty much the only ones I can't do anything about Smiley


    > the only places I had even had a moment's doubt about what the var meant was the result of the LINQ queries

    Kind of obvious thing to do is to just do many smaller queries and use good names for them and combine later. It's all too easy to build monolithic query but the point with eg. functional programming is splitting it all to super simple things then combine.

Conversation locked

This conversation has been locked by the site admins. No new comments can be made.