When should I use “this” in a class?

后端 未结 18 2184
情书的邮戳
情书的邮戳 2020-11-21 23:36

I know that this refers to a current object. But I do not know when I really need to use it. For example, will be there any difference if I use x i

18条回答
  •  情话喂你
    2020-11-22 00:07

    There are a lot of good answers, but there is another very minor reason to put this everywhere. If you have tried opening your source codes from a normal text editor (e.g. notepad etc), using this will make it a whole lot clearer to read.

    Imagine this:

    public class Hello {
        private String foo;
    
        // Some 10k lines of codes
    
        private String getStringFromSomewhere() {
            // ....
        }
    
        // More codes
    
        public class World {
            private String bar;
    
            // Another 10k lines of codes
    
            public void doSomething() {
                // More codes
                foo = "FOO";
                // More codes
                String s = getStringFromSomewhere();
                // More codes
                bar = s;
            }
        }
    }
    

    This is very clear to read with any modern IDE, but this will be a total nightmare to read with a regular text editor.

    You will struggle to find out where foo resides, until you use the editor's "find" function. Then you will scream at getStringFromSomewhere() for the same reason. Lastly, after you have forgotten what s is, that bar = s is going to give you the final blow.

    Compare it to this:

    public void doSomething() {
        // More codes
        Hello.this.foo = "FOO";
        // More codes
        String s = Hello.this.getStringFromSomewhere();
        // More codes
        this.bar = s;
    }
    
    1. You know foo is a variable declared in outer class Hello.
    2. You know getStringFromSomewhere() is a method declared in outer class as well.
    3. You know that bar belongs to World class, and s is a local variable declared in that method.

    Of course, whenever you design something, you create rules. So while designing your API or project, if your rules include "if someone opens all these source codes with a notepad, he or she should shoot him/herself in the head," then you are totally fine not to do this.

提交回复
热议问题