Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 377
Danedo Avatar asked Jan 09 '11 19:01

Danedo


People also ask

What can I use instead of this in Java?

'this' means 'current object'. In static methods there is no current object. In your example, try replacing this with new Main() .

Why do we use this in constructor?

Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this .

What happens if you dont use this in Java?

Definition and Usage The most common use of the this keyword is to eliminate the confusion between class attributes and parameters with the same name (because a class attribute is shadowed by a method or constructor parameter). If you omit the keyword in the example above, the output would be "0" instead of "5".

Why do we use this?

We use this, that, these and those to point to people and things. This and that are singular. These and those are plural. We use them as determiners and pronouns.


2 Answers

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

like image 152
jmj Avatar answered Nov 15 '22 17:11

jmj


There's no ambiguity. If there were, you'd have to use this.

Some people recommend this for clarity. Others recommend against it when it's not required, as it introduces "noise". Some modern IDEs or editors may be able to use syntax highlighting to color (for instance) arguments differently from fields for clarity.

Personally I avoid this when I can and use @unholysampler's underscore convention. Agree on something with your coworkers and put it in your coding standards.

like image 41
TrueWill Avatar answered Nov 15 '22 16:11

TrueWill