java 对象中的自引用是错误代码设计的证据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5953916/
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-10-30 13:38:28  来源:igfitidea点击:

Is a self reference in an object evidence of bad code design

javacoding-style

提问by user489041

I have come across a self reference in some code I was looking at.

我在我正在查看的一些代码中遇到了自我引用。

Example

例子

TestObject selfReference = this;

Is there ever a good case in which you would need a self reference in an object? Is this a sign of a bad coding design or style?

是否有一个很好的案例,您需要在对象中使用自引用?这是一个糟糕的编码设计或风格的标志吗?

EDIT:

编辑:

This is an example of where if I use thisit will throw an error, but when using selfReference, it compiles.

这是一个示例,如果我使用this它会抛出错误,但使用 selfReference 时,它​​会编译。


public class IFrame extends InternalFrame
{
    public IFrame()
    {
         addComponentListener(new java.awt.event.ComponentAdapter()
        {
            public void componentResized(java.awt.event.ComponentEvent evt) 
            {
                Window.setCurrComponent(this); //compile error
            }
            public void componentMoved(ComponentEvent evt)
            {
                Window.setCurrComponent(selfReference); //compiles correctly
            }
        });
    }
}

public class InternalFrame extends JInternalFrame
{
    protected InternalFrame selfReference = this;
}

public class Window
{
    InternalFrame currFrame;

    public static void setCurrComponent(InternalFrame iFrame)
    {
        currFrame = iFrame
    }
}

回答by Oliver Charlesworth

Yes, there are circumstances in which an implicitself-reference may be entirely natural. Consider, for instance, a circular linked list that currently contains only a single element.

是的,在某些情况下,隐含的自我引用可能是完全自然的。例如,考虑当前仅包含单个元素的循环链表。

However, having a member variable called selfReferencedoesn't make any sense at all.

但是,调用成员变量selfReference根本没有任何意义。

回答by Kaj

I'll take a stab on this. I'm guessing that the author of that code didn't know that you can write Classname.this when you want to access "the outer this" from a nested classs.

我会尝试一下。我猜该代码的作者不知道当您想从嵌套类访问“外部 this”时可以编写 Classname.this 。

That is, he created a construct like this:

也就是说,他创建了一个这样的结构:

class Executor {
    public void execute(Example example) {

    }
}

public class Example {

    Example selfReference = this;

    class Nested {
        public void method() {
            //Oh, oh, can't do this: 
            //new Executor().execute(this);
            //It gives:
            //The method execute(Example) in the type Executor is not applicable for the arguments (Example.Nested)

            //How the hell do I invoke the executor method from here?
            //lets do something really odd.
            new Executor().execute(selfReference);

            //This is what he should have done
            new Executor().execute(Example.this);
        }
    }

}

回答by Vladimir Dyuzhev

Not necessary.

不必要。

A perfectly valid case for self-reference is an object that needs some handler. If the object implements that handler interface itself, the reference to handler is the reference to the very same object. Totally OK, IMHO.

自引用的一个完全有效的情况是需要一些处理程序的对象。如果对象本身实现了该处理程序接口,则对处理程序的引用就是对相同对象的引用。完全可以,恕我直言。

回答by Kaypro II

I would say a self reference a sign of bad code in Java, especially if it's named something like "selfReference," because Java already has a standard self reference named "this". It's a different story in languages that support closures, since a non-this self reference can keep the "this" object in the scope of the closure.

我会说自引用是Java中错误代码的标志,尤其是当它被命名为“selfReference”时,因为 Java 已经有一个名为“this”的标准自引用。在支持闭包的语言中这是另一回事,因为非 this 自我引用可以将“this”对象保持在闭包的范围内。

回答by Liv

I would say that is a sign of bad code:

我会说这是错误代码的标志:

  • everyone knows what thismeans so I can't see the need for a reference called selfReference
  • unless of course you are planning to change that reference later on to something else -- e.g.
  • 每个人都知道是什么this意思所以我看不出需要一个称为selfReference
  • 除非您当然打算稍后将该引用更改为其他内容 - 例如

TestObject selfReference = this; //call some functions on this selfReference = someOtherObject; //where someOtherObject is an instance of TestObject as well //call some functions on someOtherObjects

TestObject selfReference = this; //在这个 selfReference = someOtherObject 上调用一些函数;//其中 someOtherObject 也是 TestObject 的一个实例 // 在 someOtherObjects 上调用一些函数

  • however, if that is the case and the reference gets re-assigned to something else at some point then it shouldn't be called selfReference-- since it can end up not referencing self/this!
  • 但是,如果是这种情况并且引用在某个时候被重新分配给其他东西,那么它不应该被调用selfReference——因为它最终可能不会引用 self/this!

回答by Isaac Truett

With the updated code sample, it looks like you're having trouble referencing the outer object from an anonymous inner class. The syntax is:

使用更新后的代码示例,您似乎无法从匿名内部类引用外部对象。语法是:

OuterClass.this

OuterClass.this

In your case:

在你的情况下:

public void componentResized(java.awt.event.ComponentEvent evt) 
{
    Window.setCurrComponent(IFrame.this); //no more compile error
}

If you just use thisalone, you are referencing the new ComponentAdapter().

如果您只是this单独使用,则您正在引用new ComponentAdapter().

Thank you for the additional context.

感谢您提供额外的上下文。

回答by Peter Lawrey

Without more context, the code doesn't do anything useful and is potentially confusing. I don't think it qualifies as "design" or "style".

没有更多的上下文,代码不会做任何有用的事情,并且可能会令人困惑。我认为它不符合“设计”或“风格”的要求。

However more context might show why it is being done.

然而,更多的上下文可能会显示为什么要这样做。

回答by hs001

Window.setCurrComponent(this); //compile error 'this' in above statement is not InternalFrame object its ComponentAdapter object, as you are in Anonymous inner class.

Window.setCurrComponent(this); //上面语句中的编译错误“this”不是其 ComponentAdapter 对象的 InternalFrame 对象,因为您在匿名内部类中。

Window.setCurrComponent(selfReference); //compiles correctly above line is correct statement if you want to reference your IFrame class' object.

Window.setCurrComponent(selfReference); //如果您想引用您的 IFrame 类对象,则正确编译以上行是正确的语句。

回答by Sarit

If you are writing a parser and have a datastructure which contains child elements of the same type then you would need to have member variables of the same class.

如果您正在编写解析器并且有一个包含相同类型子元素的数据结构,那么您将需要具有相同类的成员变量。

回答by Atticus

There's plenty of times when you want to use a this. You should in situations where you need to reference the object it belongs to. I don't see any reason to create an object out of thisthough, a simple this.attributewill suffice.

很多时候您想使用this. 您应该在需要引用它所属的对象的情况下。我认为没有任何理由创建一个对象this,一个简单的this.attribute就足够了。