Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. The Lounge
  3. Not programming, but a preference question.

Not programming, but a preference question.

Scheduled Pinned Locked Moved The Lounge
questioncollaboration
93 Posts 34 Posters 1 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • OriginalGriffO OriginalGriff

    wizardzz wrote:

    since almost every single variable is a var, it's taking quite some time to figure out why some choices were made

    That is my main dislike of var - when you are trying to read the code, you have no idea what a variable is, or what you can do with it, without looking at some other bit of code and coming back. Explicit variable typing lets you know immediately what type it is and hence what you can do with it. Besides, it's lazy. "I don't want to think about this variable, it just want to get on with the interesting stuff".

    Ideological Purity is no substitute for being able to stick your thumb down a pipe to stop the water

    S Offline
    S Offline
    Steve Crane
    wrote on last edited by
    #47

    I don't agree that using var is always lazy. It can have a place in making code more readable when declaring types with really long names. For example

    SomeClassWithAReallyReallyLongName whatever = new SomeClassWithAReallyReallyLongName();

    is (to me) less readable than

    var whatever = new SomeClassWithAReallyReallyLongName();

    The rule I follow is to use var wherever possible, but only if the declaration explicitly indicates what type the var will be. For example

    var start = new DateTime();

    or

    var start = DateTime.UtcNow;

    are acceptable while

    var data = GetData();

    is not, and should rather have the type explicitly declared.

    1 Reply Last reply
    0
    • Y YvesDaoust

      If I were you, I would first wonder how much variable types matter to me. I mean types of any variable in the project. If the types matter so much that you feel like to reflect them explicitly in the names (HN), then something must be done. You have at least three options: 1) use a prefix that indicates an implicitly typed variable (var),

           var \_\_\_Count= 0;
      

      Cheap, and uninformative. 2) use a prefix that indicates the actual type choosen by the compiler.

            var intCount= 0;
      

      Harder but gives an opportunity to improve your mastership of the code. 3) retype the variable to its proper type rather than var (and apply your standard naming policy).

            int intCount= 0;
      

      Strongest and slightly more risky (deeper refactoring). On the opposite, if you use no naming convention for the ordinary variables, why should you care more about vars ? If your concern is to improve readability without refactoring, just comment.

            int Count= 0;
            /\*int\*/ var Sum= 0;
      
      J Offline
      J Offline
      jim lahey
      wrote on last edited by
      #48

      the thing that tells me that it's an implicitly typed local variable is the keyword var. I've got a VS extension (can't remember which one, sorry) that tells me the exact type when I hover over it with the mouse. As for naming conventions, I'm of the opinion that the name should semantically express the usage, so this would be totally fine with me:

      var count = 0;

      I can tell from the name what it's there for and by the assignment I can tell it's an int. I understand that some people might get confused by this:

      var count = someObject.GetCount();

      But all the above example means is that the above *might* be a short or long, and you can mouseover the method call in the assignment if you're desperate to know the exact type you're assigning. It's a whole number of some sort. If you're assigning anything other than int, short or long from a method called GetCount(), your method naming is wrong. Using a single byte to return a count is a bit of a special case which is why I haven't mentioned it. I've also never encountered a need to do so, incidentally. For some reason I get quite annoyed when people claim using var is bad practice because it introduces bugs to the code or don't get the fact that it's not the same as dynamic typing because they think it's the same as JavaScript. var works just fine, it means I don't repeat myself all over the place and is statically typed which means it won't even compile if I've done something wrong.

      I 1 Reply Last reply
      0
      • W wizardzz

        var

        A big ugly word. I don't use them unless I really need to. Now I have a project to add to that another developer created. Cool. There are a lot of vars in here. Unavoidable, too. Now, I'm the head "developer" on this team, and basically have to know all code inside and out pretty darm well. So does it make me a dick to want to use some sort of Hungarian Notation* on these vars? [Editing for clarity] I do not mean adding var to the front, or necessarily the type (though that will be useful in some cases, that's why I mistakenly said HN) I meant using a short form abbreviation to signify what the hell the variable is for rather than just "Loc" "Cust" etc when there are many similar variables.

        R Offline
        R Offline
        Robert Neaves
        wrote on last edited by
        #49

        Yes, that makes you a dick.

        1 Reply Last reply
        0
        • L Lost User

          I do not see why people get hung up on var. (I am quite certain I will ge downvoted for this post) IMO it is cleaner.

          namespace ThirdPartynamespace
          {
          class RequiredComponent
          {
          }
          }

          ...

          namespace DifferentThirdPartyNamespace
          {
          class RequiredComponent
          {
          }
          }

          namespace Local
          {
          class Thingamajig
          {
          var component = new ThirdPartyNameSpace.RequiredComponent();
          var diffComponent = new DifferentThirdPartyNameSpace.RequiredComponent();
          //vs

            ThirdPartyNameSpace.RequiredComponent ewComponent = new ThirdPartyNameSpace.RequiredComponent();
          
           DifferentThirdPartyNameSpace.RequiredComponent ewDiffComponent = new DifferentThirdPartyNameSpace.RequiredComponent();
          

          }
          }

          Ok, so now you will say that is a rare case. Maybe it is but because this case happens (actually it happens to me alot but mostly because how I use namespaces), you should follow patterns being set. You may not be always worried about thread mishaps but you still program for it. Other reasons: Return object changes.

          Computers have been intelligent for a long time now. It just so happens that the program writers are about as effective as a room full of monkeys trying to crank out a copy of Hamlet.

          D Offline
          D Offline
          dave dolan
          wrote on last edited by
          #50

          Absolutely agree. I 'var' like a champ and my life is easier for it. The only thing that annoys me is when I run into legacy API's that return non-generic IEnumerable and you can't use it in the foreach loops! It almost makes me want to convert them to a for loop just for spite. Ok, not really on that last part.

          1 Reply Last reply
          0
          • A AspDotNetDev

            I don't see why not:

            var varAge = getAge();

            Thou mewling ill-breeding pignut!

            T Offline
            T Offline
            TheRealRarius
            wrote on last edited by
            #51

            ARGH!!!!!!! At the risk of starting another strongly-typed/weakly-typed language debate, the very concept of "var" should be excised from human history. "var" is uncontrolled polymorphism at its worst (polymorphism is great, but it must be used carefully). It's lazy and dangerous and I hate the fact that I have to use it when I use Linq.

            F A I 3 Replies Last reply
            0
            • L Lost User

              Hmmm pretty sure it is fine. For one they are not subclasses. They are classes within a namespace. This is a common confliction when working with many groups or using external resources, E.g Company a has "Camera" in their library as well as company B. So we end up with CompanyA.Camera And CompanyB.Camera For objects. That was actually the point that you must then call out the whole namespace multiple times. Or am I missing something that you are pointing out?

              Computers have been intelligent for a long time now. It just so happens that the program writers are about as effective as a room full of monkeys trying to crank out a copy of Hamlet.

              B Offline
              B Offline
              BillWoodruff
              wrote on last edited by
              #52

              Compile it, and look at the errors. best, Bill

              "The greatest mystery is not that we have been flung at random between the profusion of matter and of the stars, but that within this prison we can draw from ourselves images powerful enough to deny our nothingness." Andre Malraux

              F L 2 Replies Last reply
              0
              • T TheRealRarius

                ARGH!!!!!!! At the risk of starting another strongly-typed/weakly-typed language debate, the very concept of "var" should be excised from human history. "var" is uncontrolled polymorphism at its worst (polymorphism is great, but it must be used carefully). It's lazy and dangerous and I hate the fact that I have to use it when I use Linq.

                F Offline
                F Offline
                Fabio Franco
                wrote on last edited by
                #53

                I couldn't have put it better. You lifted a very heavy burden off my chest.

                To alcohol! The cause of, and solution to, all of life's problems - Homer Simpson ---- Our heads are round so our thoughts can change direction - Francis Picabia

                1 Reply Last reply
                0
                • N Nagy Vilmos

                  Use Application Hungarian[^]. The prefix is what the variable is for rather than what it is:

                  var codeCurrency; // the code for the currency, eg USD
                  var nameCurrency; // the name for the currency, eg Green Back

                  Personally, I'd try and get rid of non-explicit declarations where you can and only resort to Apps Hungarian when you have to use vars.


                  Panic, Chaos, Destruction. My work here is done. Drink. Get drunk. Fall over - P O'H OK, I will win to day or my name isn't Ethel Crudacre! - DD Ethel Crudacre I cannot live by bread alone. Bacon and ketchup are needed as well. - Trollslayer Have a bit more patience with newbies. Of course some of them act dumb - they're often *students*, for heaven's sake - Terry Pratchett

                  W Offline
                  W Offline
                  wizardzz
                  wrote on last edited by
                  #54

                  Nagy, thank you. I did not know the name for this, so I initially referred to it as just HN. This is exactly what I want the junior developers to start doing when we must use vars (among other things, LINQ conditions passed to API happens a lot here, too). (The one that did this is a director, but of SQL related stuff, codingwise, he's a junior).

                  1 Reply Last reply
                  0
                  • B BillWoodruff

                    My 2 cents (farthings, groats, obeloi) worth: While MS pronouncements on use of 'var have often mentioned the "economy" of not having to enter the fully qualified name of some object twice: imho, the major usage has been associated with conveniently storing the result of some LINQ-produced complex entity that you could break a tooth on trying to specify its exact type. ... begin edit #1 ... And, I forgot to say using 'var for "anonymous types" is required ! ... end edit #1 ... We've always had ways to shorten up long fully-qualified object names using the "using directive:" as in the "extreme" example offered here:

                    using System;
                    using spc1 = ThirdPartyNameSpace.RequiredComponent1;
                    using spc2 = DifferentThirdPartyNameSpace.RequiredComponent2;

                    namespace ThirdPartyNameSpace
                    {
                    // used internal here just for the 'hell' of it ...
                    internal class RequiredComponent1
                    {
                    }
                    }

                    namespace DifferentThirdPartyNameSpace
                    {
                    internal class RequiredComponent2
                    {
                    }
                    }

                    namespace Local
                    {
                    class Thingamajig
                    {
                    spc1 s1ReqComponent = new spc1();

                        spc2 s2ReqComponent = new spc2();
                    }
                    

                    }

                    Note that I am not advocating you should code this way, and, in actual practice, I usually use this only when using a 3rd. party component that really requires complex multi-dot path names to use the most commonly used elements in it. And, in that case, I would use variable names that were, indeed, mnemonic (which is not what you see here). best, Bill

                    "The greatest mystery is not that we have been flung at random between the profusion of matter and of the stars, but that within this prison we can draw from ourselves images powerful enough to deny our nothingness." Andre Malraux

                    W Offline
                    W Offline
                    wizardzz
                    wrote on last edited by
                    #55

                    That is interesting, Bill. I think that is not a bad idea for 3rd party API's. It's something I've come across, but not done myself, so it never really made it into my library of knowledge.

                    1 Reply Last reply
                    0
                    • L Lost User

                      I do not see why people get hung up on var. (I am quite certain I will ge downvoted for this post) IMO it is cleaner.

                      namespace ThirdPartynamespace
                      {
                      class RequiredComponent
                      {
                      }
                      }

                      ...

                      namespace DifferentThirdPartyNamespace
                      {
                      class RequiredComponent
                      {
                      }
                      }

                      namespace Local
                      {
                      class Thingamajig
                      {
                      var component = new ThirdPartyNameSpace.RequiredComponent();
                      var diffComponent = new DifferentThirdPartyNameSpace.RequiredComponent();
                      //vs

                        ThirdPartyNameSpace.RequiredComponent ewComponent = new ThirdPartyNameSpace.RequiredComponent();
                      
                       DifferentThirdPartyNameSpace.RequiredComponent ewDiffComponent = new DifferentThirdPartyNameSpace.RequiredComponent();
                      

                      }
                      }

                      Ok, so now you will say that is a rare case. Maybe it is but because this case happens (actually it happens to me alot but mostly because how I use namespaces), you should follow patterns being set. You may not be always worried about thread mishaps but you still program for it. Other reasons: Return object changes.

                      Computers have been intelligent for a long time now. It just so happens that the program writers are about as effective as a room full of monkeys trying to crank out a copy of Hamlet.

                      F Offline
                      F Offline
                      Fabio Franco
                      wrote on last edited by
                      #56

                      Collin Jasnoch wrote:

                      var component = new ThirdPartyNameSpace.RequiredComponent(); var diffComponent = new DifferentThirdPartyNameSpace.RequiredComponent();

                      I read this and thought: "What the hell is the type returned by this methods?" "Oh wait, these are not methods, these are fully qualified types." Can you picture the ammount of unnecessary confusion created by this code when someone else try to read it? Or even your self after sometime? This easy to write and terrible to read. If you inherit a code that has a lot of vars good luck sweeping the code to understand its purpose. If you have a printed copy of the code, well then there is no way to understand the code.

                      Collin Jasnoch wrote:

                      ThirdPartyNameSpace.RequiredComponent ewComponent = new ThirdPartyNameSpace.RequiredComponent();

                      That's what the "#using" directive is for, then you would have:

                      RequiredComponent notEwAtAllComponent = new RequiredComponent()

                      Now you have a very readable code and intellisense made it not hard to type, magic heh? When looking at the code from a mostly left to right culture I can instantly identify the type being declared. Second, if you have components with same names and different namespaces, you can make it much shorter also with the "#using" directive: #using ThirdPartyNameSpace; #using diffNS = DifferentThirdPartyNameSpace;

                      diffNS.RequiredComponent diffComponent = diffNS.RequiredComponent();

                      Lastly, var should be used for anonymous types. That's the real good use of it and shouldn't be abused like I often see. Your particular example is a hell to review.

                      To alcohol! The cause of, and solution to, all of life's problems - Homer Simpson ---- Our heads are round so our thoughts can change direction - Francis Picabia

                      Richard DeemingR L 2 Replies Last reply
                      0
                      • L Lost User

                        Hmmm pretty sure it is fine. For one they are not subclasses. They are classes within a namespace. This is a common confliction when working with many groups or using external resources, E.g Company a has "Camera" in their library as well as company B. So we end up with CompanyA.Camera And CompanyB.Camera For objects. That was actually the point that you must then call out the whole namespace multiple times. Or am I missing something that you are pointing out?

                        Computers have been intelligent for a long time now. It just so happens that the program writers are about as effective as a room full of monkeys trying to crank out a copy of Hamlet.

                        F Offline
                        F Offline
                        Fabio Franco
                        wrote on last edited by
                        #57

                        See how var can be a source of confusion?

                        To alcohol! The cause of, and solution to, all of life's problems - Homer Simpson ---- Our heads are round so our thoughts can change direction - Francis Picabia

                        L 1 Reply Last reply
                        0
                        • B BillWoodruff

                          Compile it, and look at the errors. best, Bill

                          "The greatest mystery is not that we have been flung at random between the profusion of matter and of the stars, but that within this prison we can draw from ourselves images powerful enough to deny our nothingness." Andre Malraux

                          F Offline
                          F Offline
                          Fabio Franco
                          wrote on last edited by
                          #58

                          There are no errors, just confusion for the abuse of var keyword. The types instantiated are fully qualified types, you just don't see them in the left hand side because the var keyword was used.

                          To alcohol! The cause of, and solution to, all of life's problems - Homer Simpson ---- Our heads are round so our thoughts can change direction - Francis Picabia

                          B 1 Reply Last reply
                          0
                          • T TheRealRarius

                            ARGH!!!!!!! At the risk of starting another strongly-typed/weakly-typed language debate, the very concept of "var" should be excised from human history. "var" is uncontrolled polymorphism at its worst (polymorphism is great, but it must be used carefully). It's lazy and dangerous and I hate the fact that I have to use it when I use Linq.

                            A Offline
                            A Offline
                            AspDotNetDev
                            wrote on last edited by
                            #59

                            Not sure what you mean. Using "var" in C# does not make thigns weakly typed. The variable is still strongly typed at compile time... the type is just inferred.

                            Thou mewling ill-breeding pignut!

                            1 Reply Last reply
                            0
                            • T TheRealRarius

                              ARGH!!!!!!! At the risk of starting another strongly-typed/weakly-typed language debate, the very concept of "var" should be excised from human history. "var" is uncontrolled polymorphism at its worst (polymorphism is great, but it must be used carefully). It's lazy and dangerous and I hate the fact that I have to use it when I use Linq.

                              I Offline
                              I Offline
                              IAbstract
                              wrote on last edited by
                              #60

                              I'm not near as stringent on the use of `var`. If my data types are short - e.g., string, int, List(Of T) - I use the explicit syntax for declaring the type. On the other hand, something like

                              Dictionary>

                              ...damned right I'm using `var`. It's up to the developer to make sure the variable name is meaningful - not the declaration of the data type. Yes, be responsible with the use of `var`. `var` is necessary in a few cases - as with LINQ and anonymous types. Make sure if you want an `IFoo` from a method that returns `Foo` that you cast it:

                              var foo = GetFoo() as IFoo;

                              // where GetFoo():
                              Foo GetFoo() {
                              return new Foo();
                              }

                              // and
                              class Foo : IFoo { }

                              I certainly don't recommend leaving fate in the hands of `var`. Overuse is abuse. And abusing `var` is downright lazy. But I wouldn't get that worked up about it - maybe. :-D

                              M 1 Reply Last reply
                              0
                              • W wizardzz

                                Dang, maybe I should have clarified. I meant Hungarian Notation "style", not strictly varName, etc. Example:

                                var BeginDate = item.GetType().GetProperty("BeginDate");
                                var Locations = item.GetType().GetProperty("Locations");

                                I would prefer to be

                                var propBeginDate = item.GetType().GetProperty("BeginDate");
                                var propLocations = item.GetType().GetProperty("Locations");

                                or something like that. This is more of an example of what I meant. I guess I should have initially said, am I dick for changing variables to make more sense?

                                I Offline
                                I Offline
                                IAbstract
                                wrote on last edited by
                                #61

                                Actually, I think the first example is fine. Does it matter that `BeginDate` is a property?

                                1 Reply Last reply
                                0
                                • E Espen Harlinn

                                  I use Refactor! Pro[^]. Right click on the offending var declared varable and choose 'Make explicit' and there I have a decently declared varable. I'm pretty sure other refactoring tools have a similar feature.

                                  Espen Harlinn Principal Architect, Software - Goodtech Projects & Services AS My LinkedIn Profile

                                  I Offline
                                  I Offline
                                  IAbstract
                                  wrote on last edited by
                                  #62

                                  DevEx/CodeRush will change from implicit (`var`) to explicit.

                                  1 Reply Last reply
                                  0
                                  • J Jani Giannoudis

                                    var reminds me to VB's Dim and is - from the engineering perspective - a regression. For me it's a good practice to document/describe which type of variable you are working.

                                    Cheers, Jani Giannoudis Meerazo.com - Resource Sharing Made Easy | Co-founder

                                    I Offline
                                    I Offline
                                    IAbstract
                                    wrote on last edited by
                                    #63

                                    Even when I was strictly VB, I hated 'Dim' ...I used Dim in my early days of Applesoft Basic when I was 11, IIRC.

                                    1 Reply Last reply
                                    0
                                    • F Fabio Franco

                                      There are no errors, just confusion for the abuse of var keyword. The types instantiated are fully qualified types, you just don't see them in the left hand side because the var keyword was used.

                                      To alcohol! The cause of, and solution to, all of life's problems - Homer Simpson ---- Our heads are round so our thoughts can change direction - Francis Picabia

                                      B Offline
                                      B Offline
                                      BillWoodruff
                                      wrote on last edited by
                                      #64

                                      Compile Colin's code "as is," and examine the errors. best, Bill

                                      "The greatest mystery is not that we have been flung at random between the profusion of matter and of the stars, but that within this prison we can draw from ourselves images powerful enough to deny our nothingness." Andre Malraux

                                      F 1 Reply Last reply
                                      0
                                      • F Fabio Franco

                                        Collin Jasnoch wrote:

                                        var component = new ThirdPartyNameSpace.RequiredComponent(); var diffComponent = new DifferentThirdPartyNameSpace.RequiredComponent();

                                        I read this and thought: "What the hell is the type returned by this methods?" "Oh wait, these are not methods, these are fully qualified types." Can you picture the ammount of unnecessary confusion created by this code when someone else try to read it? Or even your self after sometime? This easy to write and terrible to read. If you inherit a code that has a lot of vars good luck sweeping the code to understand its purpose. If you have a printed copy of the code, well then there is no way to understand the code.

                                        Collin Jasnoch wrote:

                                        ThirdPartyNameSpace.RequiredComponent ewComponent = new ThirdPartyNameSpace.RequiredComponent();

                                        That's what the "#using" directive is for, then you would have:

                                        RequiredComponent notEwAtAllComponent = new RequiredComponent()

                                        Now you have a very readable code and intellisense made it not hard to type, magic heh? When looking at the code from a mostly left to right culture I can instantly identify the type being declared. Second, if you have components with same names and different namespaces, you can make it much shorter also with the "#using" directive: #using ThirdPartyNameSpace; #using diffNS = DifferentThirdPartyNameSpace;

                                        diffNS.RequiredComponent diffComponent = diffNS.RequiredComponent();

                                        Lastly, var should be used for anonymous types. That's the real good use of it and shouldn't be abused like I often see. Your particular example is a hell to review.

                                        To alcohol! The cause of, and solution to, all of life's problems - Homer Simpson ---- Our heads are round so our thoughts can change direction - Francis Picabia

                                        Richard DeemingR Offline
                                        Richard DeemingR Offline
                                        Richard Deeming
                                        wrote on last edited by
                                        #65

                                        How is:

                                        diffNS.RequiredComponent diffComponent = new diffNS.RequiredComponent();
                                        // WTF? I can't find the "diffNS" namespace anywhere in the code!
                                        // Oh, wait - it's hidden in a "using" statement somewhere else in the file.
                                        // I'll just scan *the entire file* to find out what it really is, then.

                                        any easier to read than:

                                        var diffComponent = new DifferentThirdPartyNameSpace.RequiredComponent();
                                        // What? .......... Ah, I see! It's a DifferentThirdPartyNameSpace.RequiredComponent

                                        :confused:?


                                        "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                                        "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

                                        F 1 Reply Last reply
                                        0
                                        • P PIEBALDconsult

                                          ahmed zahmed wrote:

                                          var should only be used where the type can be easily ascertained

                                          No, that's wrong -- it should only be used when the developer can't know the type, as in

                                          ahmed zahmed wrote:

                                          when using LINQ

                                          Richard DeemingR Offline
                                          Richard DeemingR Offline
                                          Richard Deeming
                                          wrote on last edited by
                                          #66

                                          PIEBALDconsult wrote:

                                          it should only be used when the developer can't know the type

                                          No, that's wrong. ;P

                                          // Wrong! BAD developer!
                                          Dictionary<string, Tuple<Customer, List<Order>>> customerOrdersCache = new Dictionary<string, Tuple<Customer, List<Order>>>();

                                          // Much better! Have a banana!
                                          var customerOrdersCache = new Dictionary<string, Tuple<Customer, List<Order>>>();


                                          "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                                          "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

                                          1 Reply Last reply
                                          0
                                          Reply
                                          • Reply as topic
                                          Log in to reply
                                          • Oldest to Newest
                                          • Newest to Oldest
                                          • Most Votes


                                          • Login

                                          • Don't have an account? Register

                                          • Login or register to search.
                                          • First post
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • World
                                          • Users
                                          • Groups