Search Unity

Is using 'var' instead of specific types really ok?

Discussion in 'Scripting' started by UnbridledGames, Jul 19, 2020.

  1. UnbridledGames

    UnbridledGames

    Joined:
    May 12, 2020
    Posts:
    139
    I recently saw a video online that touted the wonders of the Rider IDE, so I downloaded the trial and have been working with it's features, having previously been using Visual Studio.

    I'm very new to C#, having a heavy background in C ages ago, and a bit of C++ sprinkled in here and there, mostly through things like Arduino coding.

    Every bit of coding I've ever learned is to type things properly. Not wasting memory by using the right types, not causing possible compiler or runtime issues by playing fast and loose with types that will work, but might not be ideal.

    After installing Rider, I have tons of declarations that are being flagged and I'm being told to simplify it by just using var (something Visual Studio never complained about). Delcare an ItemData (internal class) as var. Declare a vector2 or 3 as var. I'm seeing all those and it's making my oldschool coder brain short circuit.

    Really? Var is ok? Is it better than strictly typing these variables? Is it not better or worse, and Rider is just trying to standardize my code? Is it actually better?

    Someone reassure me that I'm not being horrifically sloppy by using var? It feels so... dirty... *shudder* :)

    Seriously though... is there any performance difference?
     
  2. eisenpony

    eisenpony

    Joined:
    May 8, 2015
    Posts:
    974
    Your variables will still be statically typed when using var. There is absolutely no change to the compiled code and static analysis works exactly the same. The only difference is the way it looks on the editor.

    It's up to you what you prefer, but I like var because it's shorter to type and easier to change the type during refactoring.
     
    Deleted User and Lethn like this.
  3. Vryken

    Vryken

    Joined:
    Jan 23, 2018
    Posts:
    2,106
    It's entirely personal preference and makes no difference when your code is compiled and executed.

    I much prefer explicit type declarations, and I'm sure there's probably a setting in Rider to disable that warning, but I wouldn't know, since I've never used Rider.
     
    Lethn, adehm and Joe-Censored like this.
  4. Suddoha

    Suddoha

    Joined:
    Nov 9, 2013
    Posts:
    2,824
    There's no performance difference. Whenever you use var, the type will be inferred based on what's assigned. So you'll still deal with strongly typed variables.

    Opinions about the usage vary a lot.
    Many people like to be explicit with type names and don't use it at all.
    Others use it when it's more than obvious what's being assigned or when type names are too long (think about generics, or even nested generics).
    Some use it nearly everywhere - I'm one of those, for various reasons.

    Anyway, when you work in a team, for someone else or for a company, you're likely going to use their conventions.
     
  5. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,909
    Personally, I would disable that inspection in Rider.

    var is really convenient, and I use it a lot. But sometimes it's important to spell out the type of a variable for code clarity and readability. If Rider flags that as a warning, I think that's a mistake.
     
    Last edited: Jul 20, 2020
  6. UnbridledGames

    UnbridledGames

    Joined:
    May 12, 2020
    Posts:
    139
    Thanks all. Really feels weird not explicitly typing a variable. I'm probably going to disable that feature in rider. Half my screen has green squiggles under variable assignments.
     
    PraetorBlue likes this.
  7. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,909
    If Rider is anything like IntelliJ (another JetBrains IDE for Java), it should be really easy to disable just that specific inspection and leave everything else alone. Happy coding!
     
  8. Neto_Kokku

    Neto_Kokku

    Joined:
    Feb 15, 2018
    Posts:
    1,751
    It's called type inference. It's not dynamic typing at all, the compiler simply infers the type at compilation time based on assignment. The C++ equivalent is the "auto" keyword. It's good to reduce type repetition in local variable initialization and iteration, but as everything, it can be misused and make code harder to read in some cases.
     
  9. UnbridledGames

    UnbridledGames

    Joined:
    May 12, 2020
    Posts:
    139
    All this new C# stuff is hard to adjust to. I spent a long time googling how the hell to free memory in C#. Then a long time to calm the twitching and existential dread I was experiencing by not freeing allocated memory, relying on some "garbage collector" to do it for me.

    I'm apparently older than I thought I was. :p

    "Back in my day, we had to free the memory used in a linked list when we were done with it! Oh the stories I could tell you whippersnappers!"

    Gotta go, my hip is acting up. Guess it's gonna rain.
     
    Jon_Huhn and Joe-Censored like this.
  10. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    I hate var, just because it turns reading someone else's code (or even my own old code) into a hassle. The worst is when people post a bit of their own code here on the forum, and every variable is declared as var without any context about what it is, and they wonder why they aren't gett much help.
     
  11. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,775
    "var" is only legal code if the type can be immediately determined in the line in which it's declared, so I'm not sure how this would be an issue in most cases? Like "var x = GetComponent<Renderer>();" makes it quite obvious what type x is. I guess if they have a method (which they wrote) that they use for the initial assignment it wouldn't be completely clear from that snippet (and I would agree that var is a poor code style choice for that kind of assignment), but I hardly ever come across a situation like that in the forums.
     
    KyleOlsen and Suddoha like this.
  12. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    Yeah I'm talking about code like:
    Code (csharp):
    1. var terribleVariableName = TerribleMethodName(variableNotEvenSeenInTheCodeSoFar);
    Not often, but I've seen it a few times here, and it is usually someone screaming that they need help quickly.
     
    Last edited: Jul 20, 2020
  13. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,909
    I sometimes use
    var
    on the forums because the person who started the thread didn't give enough context to deduce what the type of a certain variable would be (is it a Transform? A GameObject? Something else?), but I know that I can pretty much always do something like this:
    Code (CSharp):
    1. var x = Instantiate(<someone's prefab reference of unknown type>);
    2. Transform t = x.transform;
    It's a forum hack :D
     
  14. Antistone

    Antistone

    Joined:
    Feb 22, 2014
    Posts:
    2,836
    This was already touched on, but just to be a little more explicit: "var" uses an inferred type, which is different from a variant type you may have seen in languages like JavaScript, PHP, or Visual Basic.

    A variant-typed variable can change its type over the course of the program depending on what value is assigned to it, and uses extra memory to keep track of what its current type is. For instance, you could assign an integer value to the variable, and then somewhere later on you could assign a string value to the same variable.

    An inferred type has the compiler guess what type you meant based on the context of the declaration, but that guess is set in stone and can't change; as long as the compiler guesses correctly, it compiles to the same result as if you had declared the type explicitly.



    Well, that depends on what you mean by "immediately". It's legal to do this:
    Code (CSharp):
    1. double x = 7.9;
    2. var y = x;
    You can easily infer the type of y if you already know the type of x. But x might have been declared 20 lines earlier, or even in another file entirely. The type of y does not have to appear anywhere in the line of source code where it is declared.

    I've used "var" a lot in sample code I've posted to the forum, but usually only when I'm responding to a question where the types of the variables were unclear in the original, so I don't know what the actual type is. Which is surprisingly common, and sometimes even reasonable--e.g. there's lots of questions about List<T> manipulation where it really doesn't matter what "T" is, so I end up writing example code with lines like
    var currentElement = myList[index];
    , which I wouldn't normally write in my own actual programs but makes the example more generic.



    The official purpose of "var" is to be a shorthand for cases where the type is both complicated AND either (a) obvious or (b) not helpful to spell out. The typical examples are things like
    Code (CSharp):
    1.  
    2. // Type is already written explicitly on the same line, and would be tiresome to type or read twice
    3. var someCollection = new Dictionary<string, List<Queue<MapTile>>>();
    4.  
    5. // Type is some weird collection of properties composed on the fly that doesn't have a meaningful name
    6. var someEnumeration =
    7.     from WhizBang x in allMyWhizBangs
    8.     where x.foo == 7 && x.bar == 9
    9.     select new {x.name, x.serialNumber, x.color, x.flavor};
    I think "var" is fine in extreme cases, but as a rule of thumb I avoid it.
     
  15. Owen-Reynolds

    Owen-Reynolds

    Joined:
    Feb 15, 2012
    Posts:
    1,997
    It seems obvious that C# IDE's simply prefer the newest features. It's not recommending var for any more complex reason than that. And style doesn't have any deep learning curve -- for the most part, a suggestion either immediately looks better, or it doesn't. As you point out, using the real type reminds you of the type, and knowing types is important. Even in
    Vector3 d=new Vector3(x,y,z);
    , the first Vector3 makes it 3% more readable. What's the practical reason for var everywhere? I've never seen someone telling us to use var and explaining _why_. I can explain why open-curly goes on the same line (if I couldn't, I wouldn't do it that way). Sure, some style is "any way is fine, but we need to be consistent", like variable naming. But var clearly isn't one.

    Another thing to consider is that C# didn't want var at first. Other languages had it, but C# passed. Maybe they didn't like it, or more likely, they didn't think it was important enough to add yet. Var had to be added for LINQ, since some on-the-fly database types can't be written out. So now we should use it everywhere?

    Or think of it from the IDE makers point-of-view. Being current is important. Having more possible suggestions is better. It follows that we need more suggections of current features, enabled by default so you can't miss how up-to-date it is.
     
  16. Vryken

    Vryken

    Joined:
    Jan 23, 2018
    Posts:
    2,106
    Have to agree. It seems like there's a market-shift towards making programming more implicit, and I just don't see the benefit in that other than faster typing.
     
  17. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,909
    It looks really cool in tech talks. :D
     
    Vryken likes this.
  18. Vryken

    Vryken

    Joined:
    Jan 23, 2018
    Posts:
    2,106
    Got me there.
     
  19. eisenpony

    eisenpony

    Joined:
    May 8, 2015
    Posts:
    974
    I started using var when it was first released and haven't looked back ‍/shrug
     
    KyleOlsen and lordofduct like this.
  20. Madgvox

    Madgvox

    Joined:
    Apr 13, 2014
    Posts:
    1,317
    When I first started using C#, I was very much in the "always use explicit types" camp. Over time however, and perhaps due in part to my professional work requiring the use of javascript, I've grown used to defaulting to 'var'. I will attempt to outline my own reasons for using var, and respond to some of the critiques above. This isn't an attempt to convince anyone else to use 'var', just an explanation of the philosophy behind why I am okay using it. Hopefully I can shed some light for @Owen-Reynolds in giving some 'why' behind the 'what' :)

    Any decision on what syntax to use where is (or should be, in my humble opinion) based on three factors: ease of writing code, ease of reading code, and ease of modifying existing code. I'm setting aside for the moment the added constraints that operating within a larger company create, where any number of programmers may need to interact with the same piece of code over a long period of time.

    I see others in this thread downplaying the importance of being able to write code quickly. As I have been programming for longer and longer, the way I look at code has changed. I don't pay much conscious attention to what specific code I am writing -- instead, I am largely focused on achieving the end goal I have in mind. The more the language fights me on syntax, the more I am writing code instead of making programs. 'var' simply enables me to do more of the latter.

    However, programmers spend far more time reading code than writing it, and readability seems to be most people's main gripe with using 'var'. It's not an unfair criticism, as 'var' does not provide any semantic meaning on its own. There is an important point hidden inside @Joe-Censored's succinct critique of a poorly used 'var', though:

    Code (CSharp):
    1. var terribleVariableName = TerribleMethodName(variableNotEvenSeenInTheCodeSoFar);
    2.  
    In this snippet, the 'var' is actually the least offender. Far worse are the terrible names. A type declaration happens only once, for any given variable. The variable name itself is used everywhere else. If I named all of my variables single characters,
    a
    ,
    b
    ,
    c
    , etc., my code would be a nightmare to read whether I were to use explicit type declarations or not. I am a firm believer in self-documenting code, and the guideline that comments should endeavor to only explain 'why', not 'what'. A large component of this is in effective variable names. In a mirror to my comments on writing code, the more necessarily verbose the language is, the more I am reading code instead of understanding intent. I find that good variable names go way further to that end than does explicit typing. You may respond, "why not do both, then"? Fair point, but I would argue that being redundant doesn't necessarily help readability. If a variable looks like a Duck and Quacks() like a Duck, then you really don't need to specifically label it as being a Duck. I find that a lot of my variables are assigning very obvious things with very obvious variable names, like declaring a
    Transform transform
    or
    Rigidbody rigidbody
    . I find this tedious.

    'var' also has a hidden attribute that contributes towards readability that I haven't seen touched on before; it is always 4 characters long, including the space separator. It puts variable names at a consistent depth on the screen and allows for easy visual scanning.

    The utility for modifying existing code should be obvious -- if you chance the implicit type of the underlying variable, you don't have to change the declared type.

    I don't use 'var' universally though, since my loyalty is to maximizing the three factors first and foremost, and there are definitely places where 'var' is not as useful, or impossible to use. Separating declaration from assignment doesn't allow for implicit typing at all, so that's obviously out. I have gotten caught several times by the float/int convention, where I have assigned a 0 to a variable I want to be a float. For this reason I have become more explicit when declaring float/int types. This is made easier by the fact that 'float' and 'int' are both of similar length to 'var', and at least in my version of Visual Studio, highlighted in the same color.

    But what do I know, I'm one of the weirdos who spaces all my parentheses out and puts brackets on same line :D

    Code (CSharp):
    1. if( hv.x != 0 && hv.y != 0 ) {
    2.     movementQueued = true;
    3.     queuedMovement = hv;
    4.     queuedMovement.x = 0;
    5.     hv.y = 0;
    6. }
    7. if( animGraph.blockingMovement ) {
    8.     movementQueued = true;
    9.     queuedMovement = hv;
    10. } else {
    11.     PerformMovement( hv );
    12. }
     
    Suddoha, StarManta and PraetorBlue like this.
  21. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,909
    You absolute madman! A space after the left paren but not before??
     
    eisenpony and Madgvox like this.
  22. Madgvox

    Madgvox

    Joined:
    Apr 13, 2014
    Posts:
    1,317
    It gets worse! I put a space before the left paren for method declarations, but not for method calls or other block statements!

    Code (CSharp):
    1. public void UpdateInput ( Player input ) {
    2.     DoDebugInput();
    3.  
    4.     var hv = default( TilePosition );
    5.     if( input.GetNegativeButtonDown( Actions.Horizontal ) ) {
    6.         hv.x -= 1;
    7.     }
    8.  
    9.     if( input.GetButtonDown( Actions.Horizontal ) ) {
    10.         hv.x += 1;
    11.     }
    12.  
    13.     // ...
    14. }
    If there ever needed to be more proof that I am largely a solo programmer, even professionally :D

    That is why I explicitly set aside the "corporation" portion of the 'var' debate, since that culture shift changes everything. I am always coming from the perspective of what works best for me by myself, not what works best when working with others.
     
    PraetorBlue likes this.
  23. Vryken

    Vryken

    Joined:
    Jan 23, 2018
    Posts:
    2,106
    Hey, it could be worse.

    It could be a lot worse.


     
    Madgvox likes this.
  24. Madgvox

    Madgvox

    Joined:
    Apr 13, 2014
    Posts:
    1,317
    "What do you mean this isn't Python?"
     
    eisenpony and Vryken like this.
  25. WTF is this? Get away from me you monster! :O :D

    Nice pattern on the right though, my grandma used to embroidered something similar.
     
    Kurt-Dekker and Vryken like this.
  26. Suddoha

    Suddoha

    Joined:
    Nov 9, 2013
    Posts:
    2,824
    Yes, those few per cent make it absolutely clear what 'd' is supposed to be. I can read 'd' much better now.

    Irony aside, types can actually be extreme noise when you read code.

    Ask people unfamiliar with coding to guess what your code means... They are usually annoyed by all those "nonsensical" types that they've never heard of (probably don't even know that those are types, or even what a type is).

    Now, give them the same algorithm, whatever it may be ... hit point calculation or movement with self-descriptive identifiers, only use vars and when they ask, just tell'em it's something to store a value in or that it just needs to be there. They'll read it like a normal text or some math if you've done a good job picking identifiers that are easy to understand.

    You may ask, who cares about people who don't touch your code and cannot even code. Well, if a layman can understand your logic, a software developer should be capable of that, too. Simple as that.

    Most of the time you don't need actual types to understand what code does. The primary concern is logic, the sequence of instructions and operations that make up the logic step by step, a pattern that's going to be recognized whatsoever. Most of the time, you first want to read what's supposed to happen. When you want to study the concept with the types used, or when you need to fix a bug, that's where types are going to be of interest.

    Different example: collections. If there's a collection that someone stored in a local declared using 'var', anyone capable of basic English is going to understand what 'Contains' or "Add" does.
    Whether or not the best choice was made by picking an efficient collection for the problem at hand is rather a secondary concern, that's interesting if you want to optimize or just want to understand how it's done on a fine-grained level, but not if you want to understand that there's one step in your algorithm that is about checking whether you've already registered something, stored something or anything alike.

    If another software developer tells me he cannot understand what my code does, I'm sure that types won't help, at the same time I know I've probably chosen bad identifiers.

    Last but not least, there's no doubt certain textual patterns improve readability, and code may look cleaner, for some even aesthetic or utterly satisfying. I've probably watched too many of those videos. :rolleyes:
     
    Last edited: Jul 21, 2020
    Madgvox, PraetorBlue and KyleOlsen like this.
  27. Madgvox

    Madgvox

    Joined:
    Apr 13, 2014
    Posts:
    1,317
    Well stated, and touches on the same points that my post attempted to touch on, but far more clearly!

    Exactly! This is precisely what I meant when I wrote this:

     
  28. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,531
    Waaaaaaat am I looking....

    This has to be a python person who can't bare to write another language but was forced to write some Java.
     
  29. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,531
    As for the topic at hand... it's come up here several times.

    Here is what I said back in 2017, and I stand by it to this day:
    https://forum.unity.com/threads/who-ritualistically-uses-the-c-var-keyword.467590/#post-3044088

    And I definitely stand by this post:
    https://forum.unity.com/threads/who-ritualistically-uses-the-c-var-keyword.467590/#post-3045498
     
  30. MaskedMouse

    MaskedMouse

    Joined:
    Jul 8, 2014
    Posts:
    1,092
    Throughout my projects I use var as much as possible. But the usage of var vs strong typed has always been an ancient discussion.
    I use var because it encourages me to think of better variable names that fit the variable type. And in my opinion code looks cleaner as well.
     
    Madgvox and Suddoha like this.
  31. csofranz

    csofranz

    Joined:
    Apr 29, 2017
    Posts:
    1,556
    You have been reported to the UN High Council of Crimes against Humanity
     
    Suddoha likes this.
  32. Owen-Reynolds

    Owen-Reynolds

    Joined:
    Feb 15, 2012
    Posts:
    1,997
    Using var to left-justify variable names so they line up vertically sounds good. But then you remember you've written programs and never cared about that. I've had variables left-edges line-up, and not line up, and it doesn't matter either way. If it did, we'd have noticed and all just hit tab after the type.

    Getting out an idea more quickly -- on examination I don't think it's true.
    var L=new List<int>()
    seems like less typing than
    List<int> L = new List<int>()
    , but intellisense will write the last half of the second. Either way you type List<int> once. Mentally, in
    var L=
    you still have to stop and think "list or array", "int or float". It's the same thought process, var or explicit type. I don't think var saves thinking or typing.

    MaskedMouse's var helping with better names makes sense -- not having the type next to it could help pick a name that stands on it's own. But anything can make sense, writing the type out first could help concentrate your mind more. But for real, don't most people write variable names on paper or UML diagrams, or have a naming scheme ahead of time?

    var vs. a written-out type isn't a big deal, but the OP asked and JetBrains apparently makes a big deal out of it without considering whether it might be slightly worse.
     
  33. Madgvox

    Madgvox

    Joined:
    Apr 13, 2014
    Posts:
    1,317
    I never claimed that that was my strongest point by any means! It is a fair point that minor formatting differences really don't make a huge impact on code readability, especially since syntax highlighting will often make the components of a line much clearer to parse. However, I have become pretty anal about having all my code bits line up nicely, and I have indeed noticed a marked contrast between later readability in code in which I don't care (eg. jam code), and code in which I do. Having variables line up automatically is a very minor but nice bonus provided by 'var', and every little bit of clarity helps!

    If declaring variables consisted entirely of directly instantiating classes, I might agree with you there. However, that benefit becomes non-existent in basically all other cases. Declaring variables from return values, making copies of other variables or members, etc.

    Additionally, in that specific case, I dislike the redundancy of declaring the type, and then on the same line having another indication of the variable type. I don't wish to make it seem like this is anything other than my own personal style -- I am really not trying to convince anyone to switch.

    Good point! It's true that if you're declaring a variable from scratch you will always need to take some time to consider what type you want it to be. But I refer back to my previous point -- there are far more use-cases for declaring variables than creating new objects.

    Consider the contrived hypothetical where I am declaring a new variable from some method
    Actor.GetRoutine
    that returns the interface
    IActorRoutine
    . If I am in code-land, I am thinking about "routines" and things that "routines" can do in the abstract logical sense -- rather than thinking specifically of the interface "IActorRoutine". If I write the line of code
    var routine = Actor.GetRoutine();
    , I never have to consciously care what specific type GetRoutine returns as I'm coding. I can then go on to write
    routine.GetTaskByIndex()
    or what have you (assisted by intellisense), and my flow never breaks to remind myself "ah yes, that returns an IActorRoutine".

    No disagreement there, I don't like using JetBrains products because of how intrusive they are on the editing experience -- and no, I don't want to sift through the millions of options to turn everything off, I just want it to do what I need it to from the get go, and no more! I've tried ReSharper twice, and uninstalled it shortly afterwards both times.

    And yes, absolutely. In the grand scheme of things, var vs. type is a very minor nitpick. It's those dang bracket-next-line people who are the real scourge!
     
  34. Owen-Reynolds

    Owen-Reynolds

    Joined:
    Feb 15, 2012
    Posts:
    1,997
    I somewhat buy the argument that var is good for intermediate variables when banging out experimental code. But even with that, the suggestions to convert aren't good. If you've already taken the time to write out the complete type, a button labelled "convert to
    var
    ?" wastes even more time..

    But the internet had 2/3rds of a neat idea how to use var: if you can flip around the suggestion mode, you could type
    var e1=Enemies[n]
    , then click the "convert var into its explicit type?" suggestion. It will replace var with Transform, or GameObject, or EnemyScript. It's basically an auto-complete.

    But var for quick code doesn't seem that great (without the autocomplete trick). If I'm going to use e1, I probably have to know the type. I may as well look it up (by mousing over Enemies) and write it down. Declaring e1 as var just delays that. I suppose an exception might be "it's always a Dictionary<string,int>; all of these are, and everyone knows it by heart. They don't need to see it 3 more times".
     
  35. eisenpony

    eisenpony

    Joined:
    May 8, 2015
    Posts:
    974
    This is exactly the point of var. Enemies [n] is an enemy.

    Why care what "type" it is? The compiler will correct me if my assumption is wrong, and otherwise the highly technical, computer-cares-about-it type doesn't get in my way.

    Code (csharp):
    1. var enemy = Enemies[n];
    2. var enemysAbilities  = enemy.Abilities
    Is enemysAbilities a List? A List<Ability>? An ICollection? IAbilityList? Who cares! Intellisense will help me continue not caring.
     
    Last edited: Jul 25, 2020
    Suddoha and Madgvox like this.
  36. csofranz

    csofranz

    Joined:
    Apr 29, 2017
    Posts:
    1,556
    IMHO, you answer your own question. Why care? Well, put it this way: how do you know that enemy has an attribute 'Abilities'? Because you, while writing the code, have internalized the substituted type. Fast forward three months, or perhaps switch to another coder, and that is no longer true. At the least, it'll interrupt your maintenance flow. At worst, it'll obscure coding flaws.

    It's not a big thing, agreed, but to me it reeks of sloppiness during coding, the eternal 'I'll come back and fix this later' attitude we all (well, me for sure :) ) have and that *will* come back to bite us in the butt. Because we almost never come back, and our code is now littered with opaque little black boxes that prevents good code from becoming great.
     
  37. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,531
    How does "var enemy" vs "Enemy enemy" help in knowing if Abilities is an attribute of Enemy? Both don't carry that information.

    I think this is subjective. Some people like it, others don't. You have reasons A,B,C to avoid, eisenpony and others have reasons X,Y,Z to use it.

    At the end of the day 'var' does not break anything, the compiler knows its way around it because if it can't infer the type it won't compile. It assists some in making things more aesthetically readable, while it annoys others because they feel it reduces readability. But in the end it's not wrong/bad... it's just taste. I don't like mushrooms, I don't make threads arguing why people who do... shouldn't.

    It feels like an English argument about contractions. Some loving it because it makes writing easier and aesthetically pleasing, others hating it because it removes information. And yes, this was an argument in the English world... hence "ain't ain't a word"... yes it is. It means "am not".

    Quit your bitching and lets go code!
     
    Last edited: Jul 25, 2020
    Madgvox and Suddoha like this.
  38. eisenpony

    eisenpony

    Joined:
    May 8, 2015
    Posts:
    974
    You've missed my point. I've not internalized the type because I don't need to.

    An indexed object in a collection called Enemies is an enemy. Maybe it's actually a class Mob or class Monster or an interface ICharacter<Gobbledygook> but it doesn't matter. In this context, "enemy", plus the tools of my IDE, is enough for my puny brain to continue.

    I know enemies have abilities because I've discussed the mental model of the game with a designer or another developer, or because I've been here before, once, a long time ago. I didn't know for sure they were in a property called Abilities rather than one called Skillz, or only accessible through another domain object, but I did know the abilities were in there somewhere. Intelisense was my guide, not memorizing the types. If this assumption was wrong, or changes, the compiler catches the problem, just as it would if the variable was typed explicitly as Enemy.

    If my tooling will carry a weight for me, I let it. What I don't use remembering types and their members, I can put towards thinking about my architecture and algorithm.
     
    Last edited: Jul 25, 2020
    Madgvox, MaskedMouse and Suddoha like this.
  39. Owen-Reynolds

    Owen-Reynolds

    Joined:
    Feb 15, 2012
    Posts:
    1,997
    So you agree Rider IDE is making a terrible suggestion in this case? Someone declare variables using the explicit type; Rider knows
    var
    isn't better, and can see that person clearly prefers the explicit style, but suggests the change anyway,

    To be fair to Rider, their reasoning must be: look, we all know var is slightly worse, but Rider for C# is mostly used by enterprise C#-users. Tjey use var everywhere. If they decided all variables needed an odd number of letters, we'd have a suggestion for that. But you're a game programmer, right? So you know the keybindings a game comes with are for noobs, You expect to spend 1/2-hour making them useful, so what's the problem?
     
  40. olejuer

    olejuer

    Joined:
    Dec 1, 2014
    Posts:
    211
    You won't find a consesus on this. But the warning is configurable (very easily). So I really don't get the fuss. You can even share preferred warnings with your team by export/import. I recommend doing that. var certainly isn't "better" or "worse" than explicit types, but a matter of preference. Whether it makes your code more readable or less so depends on the overall code style.
     
    Suddoha and lordofduct like this.
  41. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,531
    I wouldn't say it's "terrible". But I wouldn't say it's necessarily correct either. It is what I'd expect from Rider.

    Rider/JetBrains has their conventions, it's a highly popular convention (resharper and it's code analysis is used a lot), Jetbrains probably assumes that if you purchased Rider you probably are seeking the tools/conventions other Jetbrains products put forth.

    So yeah, I'd expect Rider to enforce its known/popular conventions as its default.

    I expect it because the inverse would be that I, and the majority of JetBrains users (Unity is a minority here), spend money on a product expecting to get integrated features that I'm familiar with from its suite of Visual Studio extensions. I start it up, and it doesn't behave how I'm used to. I would be confused/bothered as a user since this is the reason I purchased their product.

    Now... I know in resharper you can disable various aspects of its code analysis based on your own preferences. I assume Rider also has the option in its configuration. If it doesn't, then I'd agree that is terrible. It shouldn't force you to use its convention by constantly throwing warnings at you and have no way to turn that off. But I doubt Rider has restricted that configuration (especially since @olejuer has already mentioned that it is configurable)

    The only other option is that Rider uses some type of AI algorithm to "learn" your habits and cater a code standard based on that. Which is completely counter to what JetBrains has offered for years. Keep in mind, JetBrain's code analysis is designed to enforce coding style, not to embrace your unique coding style. If I as a lead of a team gave this tool to my team, and each IDE "learned" each dev's style and enforced that for the dev. Then it's doing the opposite of what I wanted... that being enforcing a common code style for all my devs to create consistent code across my team. It just so happens that the popular coding styles out there prefer 'var', where as clearly many members here don't.

    ...

    TLDR;

    Rider wasn't designed for Unity users.

    Rider was designed for the Enterprise space, and those who are familiar with the conventions of the Enterprise space.

    C# has most of its user space in the Enterprise realm.

    So I, a primarily Enterprise user (Unity/games is my hobby), am not surprised that Rider caters towards that user space by default.

    If you don't like it, go and change the configuration.
     
    Last edited: Jul 27, 2020
    Suddoha likes this.