Is passing 'this' in a method call accepted practice in java

Is it good/bad/acceptable practice to pass the current object in a method call. As in:

public class Bar{
    public Bar(){}

    public void foo(Baz baz){
        //  modify some values of baz
    }
}

public class Baz{
    //constructor omitted

    public void method(){
        Bar bar = new Bar();
        bar.foo(this);
    }
}

Specifically, is the line bar.foo(this) acceptable?


Solution 1:

There's nothing wrong with that. What is NOT a good practice is to do the same inside constructors, because you would give a reference to a not-yet-completely-initialized object.

There is a sort of similar post here: Java leaking this in constructor where they give an explanation of why the latter is a bad practice.

Solution 2:

There's no reason not to use it, this is the current instance and it's perfectly legitimate to use. In fact there's often no clean way to omit it.

So use it.

As it's hard to convince it's acceptable without example (a negative answer to such a question is always easier to argument), I just opened one of the most common java.lang classes, the String one, and of course I found instances of this use, for example

1084        // Argument is a String
1085        if (cs.equals(this))
1086            return true;

Look for (this in big "accepted" projects, you won't fail to find it.

Solution 3:

Yes, but you should be careful about two things

  1. Passing this when the object has not been constructed yet (i.e. in its constructor)
  2. Passing this to a long-living object, that will keep the reference alive and will prevent the this object from being garbage collected.

Solution 4:

It's perfectly normal and perfectly acceptable.