How to name variables

前端 未结 24 1209
抹茶落季
抹茶落季 2020-12-01 00:37
  • What rules do you use to name your variables?
  • Where are single letter vars allowed?
  • How much info do you put in the name?
  • How about for exam
相关标签:
24条回答
  • 2020-12-01 01:06

    These are all C# conventions.

    Variable-name casing

    Case indicates scope. Pascal-cased variables are fields of the owning class. Camel-cased variables are local to the current method.

    I have only one prefix-character convention. Backing fields for class properties are Pascal-cased and prefixed with an underscore:

    private int _Foo;
    public int Foo { get { return _Foo; } set { _Foo = value; } }
    

    There's some C# variable-naming convention I've seen out there - I'm pretty sure it was a Microsoft document - that inveighs against using an underscore prefix. That seems crazy to me. If I look in my code and see something like

    _Foo = GetResult();
    

    the very first thing that I ask myself is, "Did I have a good reason not to use a property accessor to update that field?" The answer is often "Yes, and you'd better know what that is before you start monkeying around with this code."

    Single-letter (and short) variable names

    While I tend to agree with the dictum that variable names should be meaningful, in practice there are lots of circumstances under which making their names meaningful adds nothing to the code's readability or maintainability.

    Loop iterators and array indices are the obvious places to use short and arbitrary variable names. Less obvious, but no less appropriate in my book, are nonce usages, e.g.:

    XmlWriterSettings xws = new XmlWriterSettings();
    xws.Indent = true;
    XmlWriter xw = XmlWriter.Create(outputStream, xws);
    

    That's from C# 2.0 code; if I wrote it today, of course, I wouldn't need the nonce variable:

    XmlWriter xw = XmlWriter.Create(
       outputStream, 
       new XmlWriterSettings() { Indent=true; });
    

    But there are still plenty of places in C# code where I have to create an object that you're just going to pass elsewhere and then throw away.

    A lot of developers would use a name like xwsTemp in those circumstances. I find that the Temp suffix is redundant. The fact that I named the variable xws in its declaration (and I'm only using it within visual range of that declaration; that's important) tells me that it's a temporary variable.

    Another place I'll use short variable names is in a method that's making heavy use of a single object. Here's a piece of production code:

        internal void WriteXml(XmlWriter xw)
        {
            if (!Active)
            {
                return;
            }
            xw.WriteStartElement(Row.Table.TableName);
    
            xw.WriteAttributeString("ID", Row["ID"].ToString());
            xw.WriteAttributeString("RowState", Row.RowState.ToString());
    
            for (int i = 0; i < ColumnManagers.Length; i++)
            {
                ColumnManagers[i].Value = Row.ItemArray[i];
                xw.WriteElementString(ColumnManagers[i].ColumnName, ColumnManagers[i].ToXmlString());
            }
            ...
    

    There's no way in the world that code would be easier to read (or safer to modify) if I gave the XmlWriter a longer name.

    Oh, how do I know that xw isn't a temporary variable? Because I can't see its declaration. I only use temporary variables within 4 or 5 lines of their declaration. If I'm going to need one for more code than that, I either give it a meaningful name or refactor the code using it into a method that - hey, what a coincidence - takes the short variable as an argument.

    How much info do you put in the name?

    Enough.

    That turns out to be something of a black art. There's plenty of information I don't have to put into the name. I know when a variable's the backing field of a property accessor, or temporary, or an argument to the current method, because my naming conventions tell me that. So my names don't.

    Here's why it's not that important.

    In practice, I don't need to spend much energy figuring out variable names. I put all of that cognitive effort into naming types, properties and methods. This is a much bigger deal than naming variables, because these names are very often public in scope (or at least visible throughout the namespace). Names within a namespace need to convey meaning the same way.

    There's only one variable in this block of code:

            RowManager r = (RowManager)sender;
    
            // if the settings allow adding a new row, add one if the context row
            // is the last sibling, and it is now active.
            if (Settings.AllowAdds && r.IsLastSibling && r.Active)
            {
                r.ParentRowManager.AddNewChildRow(r.RecordTypeRow, false);
            }
    

    The property names almost make the comment redundant. (Almost. There's actually a reason why the property is called AllowAdds and not AllowAddingNewRows that a lot of thought went into, but it doesn't apply to this particular piece of code, which is why there's a comment.) The variable name? Who cares?

    0 讨论(0)
  • 2020-12-01 01:07

    Well it all depends on the language you are developing in. As I am currently using C# I tend you use the following.

    camelCase for variables.

    camelCase for parameters.

    PascalCase for properties.

    m_PascalCase for member variables.

    Where are single letter vars allows? I tend to do this in for loops but feel a bit guilty whenever I do so. But with foreach and lambda expressions for loops are not really that common now.

    How much info do you put in the name? If the code is a bit difficult to understand write a comment. Don't turn a variable name into a comment, i.e . int theTotalAccountValueIsStoredHere is not required.

    what are your preferred meaningless variable names? (after foo & bar) i or x. foo and bar are a bit too university text book example for me.

    why are they spelled "foo" and "bar" rather than FUBAR? Tradition

    0 讨论(0)
  • 2020-12-01 01:07

    What rules do you use to name your variables? I've switched between underscore between words (load_vars), camel casing (loadVars) and no spaces (loadvars). Classes are always CamelCase, capitalized.

    Where are single letter vars allows? Loops, mostly. Temporary vars in throwaway code.

    How much info do you put in the name? Enough to remind me what it is while I'm coding. (Yes this can lead to problems later!)

    what are your preferred meaningless variable names? (after foo & bar) temp, res, r. I actually don't use foo and bar a good amount.

    0 讨论(0)
  • 2020-12-01 01:07
    1. Use variables that describes clearly what it contains. If the class is going to get big, or if it is in the public scope the variable name needs to be described more accurately. Of course good naming makes you and other people understand the code better.
      • for example: use "employeeNumber" insetead of just "number".
      • use Btn or Button in the end of the name of variables reffering to buttons.
    2. Start variables with lower case, start classes with uppercase.
      • example of class "MyBigClass", example of variable "myStringVariable"
    3. Use upper case to indicate a new word for better readability. Don't use "_", because it looks uglier and takes longer time to write.
      • for example: use "employeeName".
    4. Only use single character variables in loops.
    0 讨论(0)
  • 2020-12-01 01:09

    Pretty much every modern language that had wide use has its own coding standards. These are a great starting point. If all else fails, just use whatever is recommended. There are exceptions of course, but these are general guidelines. If your team prefers certain variations, as long as you agree with them, then that's fine as well.

    But at the end of the day it's not necessarily what standards you use, but the fact that you have them in the first place and that they are adhered to.

    0 讨论(0)
  • 2020-12-01 01:12

    It's pretty much unimportant how you name variables. You really don't need any rules, other than those specified by the language, or at minimum, those enforced by your compiler.

    It's considered polite to pick names you think your teammates can figure out, but style rules don't really help with that as much as people think.

    0 讨论(0)
提交回复
热议问题