Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 this it will throw an error, but when using selfReference, it compiles.


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

like image 785
user489041 Avatar asked Dec 07 '25 08:12

user489041


1 Answers

Yes, there are circumstances in which an implicit self-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 selfReference doesn't make any sense at all.

like image 69
Oliver Charlesworth Avatar answered Dec 08 '25 22:12

Oliver Charlesworth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!