Alex Rivera | Logout

In OOP, what is the best practice in regards to using "this" inside a class?

Asked 2011-01-09T19:17:59.557
12

Something I've always wondered; in a class where you can reference a member by either using 'this.[NAME]' or simply [NAME], which is preferred?

For example in Java:

public class foo {
    public int bars = 0;
    private void incrementBars(){
        bars++;
    }
}   

and

public class foo {
    public int bars = 0;
    private void incrementBars(){
        this.bars++;
    }
}

'seem' to have the same effect.

In cases where I instantiate multiple instances of class foo, I'd, so far, do something like:

for (foo f : listOfFoos){
    f.incrementBars();
}

and it seems to still work.

Is it technically ambiguous, and if so is there a preferred way?

Edit
Report

3 Answers

20

use this in the case of variable shadowing.

 class MyClass{
        int i;//1
        public void myMethod(){
            i = 10;//referring to 1    
        }

        public void myMethod(int i){//2
            i = 10;//referring to 2
            this.i = 10 //refering to 1    
        }    
    }  

also sometime this will make code more readable due to our English mindset

answered 2011-01-09T19:19:26.423
3

The only time you need this. is when the current scope also has a variable of the same name. I prefer to use the convention of _variable for all class variables. This way I never have to use this. and never accidentally touch a class variable thinking it was a locally scoped variable.

answered 2011-01-09T19:23:10.243
0

It is technically ambiguous except in the case of where you have variable shadowing (which Jigar pointed out in his answer).

Most often if you working in an editor / IDE that is very aware of your class structure syntax highlighting will make it obvious as to whether or not a variable is field in the object or just a variable defined in a method. However, in more pure text editors (vim, for instance)the syntax highlighting doesn't make this clear.

With that said, I prefer using this.field to refer to all fields that belong in the object if only because I know that every now and then I'll be reading code outside of my normal IDEs. It is marginally more verbose, but that's a tradeoff I don't mind.

answered 2011-01-09T19:35:13.543

Your Answer