Why do we use _ in variable names?

前端 未结 11 1818
一生所求
一生所求 2020-12-25 11:26

I have seen variables like _ image and was wondering what _ meant?

相关标签:
11条回答
  • Usually it separates class fields from the variables. To avoid using this in code constructions.

    class MyClass {
    
     private int _myIntField;
    
    
        private void setMyIntField(int value2Set) {
         _myIntField = value2Set;
        }
    
    }
    
    0 讨论(0)
  • 2020-12-25 12:04

    It doesn't mean anything. It is rather a common naming convention for private member variables to keep them separated from methods and public properties. For example:

    class Foo
    {
       private int _counter;
    
       public int GetCounter()
       {
          return _counter;
       }
    
       public int SetCounter(int counter)
       {
          _counter = counter;
       }
    }
    
    0 讨论(0)
  • 2020-12-25 12:07

    In most languages, it doesn't actually affect the functionality of the code, but is often used to denote reserved or internal names.

    It is common in some languages to name your instance variable _image or image_ and then make the public method used to access it image().

    Similarly, some names like __FILE__ are used in some languages to denote a special variable or constant created by the interpreter or compiler; such names are often reserved to encourage programmers to avoid using those names in their own programs in case the names are used in future versions of the language.

    0 讨论(0)
  • 2020-12-25 12:10

    Another use case (mainly in javascript) is when you need to assign the current instance this to a local variable we write as below

    var _this = this;
    

    If you need to create a local temporary object reference, to differentiate between the actual needed reference, we create as below

    List<Employee> employeeList = new ArrayList<>();
    for (Employee _employee : employeeList) {}
    

    So if we follow this best practice, every time you see a variable with _ , we come to a conclusion that its being used to solve some business need at that particular method.

    0 讨论(0)
  • 2020-12-25 12:14

    Well Underscore character(_) begin with your variable name is discouraged but it is legal and some people use it to identify as an private variable and some for naming it in caching variable. Go through with this link too.

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