diestl
diestl

Reputation: 2058

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?

Upvotes: 96

Views: 21280

Answers (10)

Denys Séguret
Denys Séguret

Reputation: 382102

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.

Upvotes: 155

Petr Zelenka
Petr Zelenka

Reputation: 63

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).

Upvotes: 2

Suresh Atta
Suresh Atta

Reputation: 121998

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.

Upvotes: 4

JW.
JW.

Reputation: 4951

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.

Upvotes: 5

Stefanos T.
Stefanos T.

Reputation: 550

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.

Upvotes: 42

morgano
morgano

Reputation: 17422

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.

Upvotes: 166

Nargis
Nargis

Reputation: 4787

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.

Upvotes: 1

blganesh101
blganesh101

Reputation: 3695

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.

Upvotes: 0

Juned Ahsan
Juned Ahsan

Reputation: 68715

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.

Upvotes: 5

Bathsheba
Bathsheba

Reputation: 234655

It's perfectly normal and perfectly acceptable.

Upvotes: 13

Related Questions