在 Java 中接受的方法调用实践中传递“this”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17441871/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 02:00:04  来源:igfitidea点击:

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

java

提问by maxf130

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?

具体来说,线路是否bar.foo(this)可以接受?

回答by morgano

There's nothing wrong with that. What is NOT a good practiceis 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 constructorwhere they give an explanation of why the latter is a bad practice.

这里有一种类似的帖子:Java 在构造函数泄漏了这个,他们解释了为什么后者是一种不好的做法。

回答by Denys Séguret

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

没有理由不使用它,this是当前实例并且使用它是完全合法的。事实上,通常没有干净的方法可以省略它。

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.langclasses, the Stringone, and of course I found instances of this use, for example

由于没有例子很难说服它是可以接受的(对这样一个问题的否定答案总是更容易争论),我刚刚打开了一个最常见的java.lang类,String一个,当然我发现了这种用法的实例,例如

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

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

查找(this在大“接受”的项目,你不会不发现它。

回答by Stefanos T.

Yes, but you should be careful about two things

是的,但你应该注意两件事

  1. Passing thiswhen 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 thisobject from being garbage collected.
  1. 在对象尚未构造时(即在其构造函数中) 传递此参数
  2. 将 this 传递给一个长期存在的对象,这将使引用保持活动状态并防止this对象被垃圾收集。

回答by Bathsheba

It's perfectly normal and perfectly acceptable.

这是完全正常的,完全可以接受的。

回答by Juned Ahsan

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.

this 代表当前对象。您所做的在语法上是正确的,但如果您在同一个类中调用该方法,我认为不需要这样做。

回答by Suresh Atta

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.

是的。你可以使用它。它只是在编程中很常见this。但是使用它有利有弊。仍然这样做没有危险。

回答by JW.

It is bad practiceto 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 thisis passed from one object to another.

根据定义,一旦this从一个对象传递到另一个对象,就会创建双向关联。

To quote Refactoring, by Martin Fowler:

引用 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.

将双向关联更改为单向 (200)

双向关联很有用,但它们有代价。代价是维护双向链接和确保正确创建和删除对象增加了复杂性。双向关联对许多程序员来说并不自然,因此它们通常是错误的来源

...

您应该在需要时使用双向关联,而在不需要时则不使用。一旦您看到双向关联不再发挥其作用,请放弃不必要的一端。

So, theoretically, we should be hearing alarm bells when we find we need to pass thisand 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.

因此,从理论上讲,当我们发现需要通过时,我们应该听到警钟,this并努力想出其他方法来解决手头的问题。当然,有时候,在不得已的情况下,这样做是有意义的。

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 massivelyby avoiding bidirectional links like the plague.

在实践中,我发现通过避免像瘟疫这样的双向链接,我的代码得到了极大的改进。

回答by Petr Zelenka

Just to add one more example where passing thisis 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).

只是添加一个this正确的传递并遵循良好设计的示例:访问者模式。在访问者设计模式中,方法accept(Visitor v)通常以调用的方式实现v.visit(this)

回答by Nargis

Acceptable

可接受

Snippet from Oracle JAVA docs:

来自 Oracle JAVA 文档的片段:

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.

在实例方法或构造函数中, this 是对当前对象的引用——正在调用其方法或构造函数的对象。您可以使用 this 从实例方法或构造函数中引用当前对象的任何成员。

将此与字段一起使用

使用 this 关键字的最常见原因是因为字段被方法或构造函数参数遮蔽。

回答by blganesh101

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.

java中的一切都是按值传递的。但是对象永远不会传递给方法!
当 java 将一个对象传递给一个方法时,它首先创建一个对象引用的副本,而不是对象本身的副本。因此这是java中完美使用的方法。最常遵循的用法。