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

Java

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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: https://stackoverflow.com/questions/9851813/java-leaking-this-in-constructor where they give an explanation of why the latter is a bad practice.

Solution 2 - Java

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 - Java

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 - Java

It's perfectly normal and perfectly acceptable.

Solution 5 - Java

this stands for the current object. What you are doing is sytatically correct but i don't see a need of this if you are calling the method in the same class.

Solution 6 - Java

Yes. you can use it.Its just common in programming to pass this.But there are pros and cons about using that.Still it is not hazardous to do so.

Solution 7 - Java

It is bad practice to pass the current object in a method call if there less complex alternatives to achieve the same behaviour.

By definition, a bidirectional association is created as soon as this is passed from one object to another.

To quote Refactoring, by Martin Fowler:

> Change Bidirectional Association to Unidirectional (200) > > Bidirectional associations are useful, but they carry a price. The > price is the added complexity of maintaining the two-way links and > ensuring that objects are properly created and removed. Bidirectional > associations are not natural for many programmers, so they often are a > source of errors

> ...

> You should use bidirectional associations when you need to but not > when you don’t. As soon as you see a bidirectional association is no > longer pulling its weight, drop the unnecessary end.

So, theoretically, we should be hearing alarm bells when we find we need to pass this and try really hard to think of other ways to solve the problem at hand. There are, of course, times when, at last resort, it makes sense to do it.

Also it is often necessary to corrupt your design temporarily, doing 'bad practice things', during a longer term refactoring of your code for an overall improvement. (One step back, two steps forward).

In practice I have found my code has improved massively by avoiding bidirectional links like the plague.

Solution 8 - Java

Just to add one more example where passing this is correct and follows good design: Visitor pattern. In Visitor design pattern, method accept(Visitor v) is typically implemented in a way it just calls v.visit(this).

Solution 9 - Java

Acceptable

Snippet from Oracle JAVA docs:

> 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. > > Using this with a Field > > The most common reason for using the this keyword is because a field > is shadowed by a method or constructor parameter.

Solution 10 - Java

Everything in java is passed by value. But objects are NEVER passed to the method!
When java passes an object to a method, it first makes a copy of a reference to the object, not a copy of the object itself. Hence this is pefectly used method in java. And most commonly followed usage.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionmaxf130View Question on Stackoverflow
Solution 1 - JavamorganoView Answer on Stackoverflow
Solution 2 - JavaDenys SéguretView Answer on Stackoverflow
Solution 3 - JavaStefanos T.View Answer on Stackoverflow
Solution 4 - JavaBathshebaView Answer on Stackoverflow
Solution 5 - JavaJuned AhsanView Answer on Stackoverflow
Solution 6 - JavaSuresh AttaView Answer on Stackoverflow
Solution 7 - JavaJW.View Answer on Stackoverflow
Solution 8 - JavaPetr ZelenkaView Answer on Stackoverflow
Solution 9 - JavaNargisView Answer on Stackoverflow
Solution 10 - Javablganesh101View Answer on Stackoverflow