27

Is it ever justified to have an object which has itself as a field like this :

class Thing {

    Thing field;

    public Thing() {
        this.field = this;
    }
}

I'm not talking about a class with a field of the same type but a class made so that every instance of the class has itself as a field. I just saw this in some legacy code (this field was never used) so I'm curious. Any legit use of this ?

Huang Chen
  • 1,177
  • 9
  • 24
Autar
  • 1,589
  • 2
  • 25
  • 36
  • 1
    A TreeNode used in representing any kind of a Tree – 6ton Jul 27 '15 at 13:25
  • 4
    No, this.field is a redundant info. No real use for it. – Andrei G Jul 27 '15 at 13:26
  • 3
    "this" object referece cannot be changed at runtime. Declaring a field of type "Thing" allows you to chande it during program execution. Suppose you define a class OtherThing that extends Thing. In that case you could override some methods. In that case the field reference could have some meaning. – Luca Putzu Jul 27 '15 at 13:50
  • @LucaPutzu: I can't see a use for it in a subclass; you don't need the `field` variable because you could just use `super` instead. – nickgrim Jul 27 '15 at 21:37
  • 1
    There are cases when you build a data structure and have a pointer that needs to be followed to walk around the structure. In those cases self pointers are often used as a simply way of saying "I'm the root" or "I'm a leaf" etc. you could argue: just use a `null` pointer. Yes, but it may happen that the algorithm wants to actually perform some operation on the pointed object and it can happen that using a self-loop making things work and simplifies the code removing redundant checks. – Bakuriu Jul 28 '15 at 05:28

9 Answers9

38

Yes, though this is rare. This is used in the JDK for situations which the field could be this but it might not be.

From the class which implements Collections.synchronizedCollection(c)

static class SynchronizedCollection<E> implements Collection<E>, Serializable {
    private static final long serialVersionUID = 3053995032091335093L;

    final Collection<E> c;  // Backing Collection
    final Object mutex;     // Object on which to synchronize

    SynchronizedCollection(Collection<E> c) {
        this.c = Objects.requireNonNull(c);
        mutex = this;
    }

    SynchronizedCollection(Collection<E> c, Object mutex) {
        this.c = Objects.requireNonNull(c);
        this.mutex = Objects.requireNonNull(mutex);
    }

In this case the mutex might be the current class, however if this collection is obtained from an existing synchronised collection, the mutex might be different. e.g. if you call Map.values() and the Map is a synchronizedMap the mutex will be the map not the collection.


Another example is Throwable which points to itself as the cause by default.

/**
 * The throwable that caused this throwable to get thrown, or null if this
 * throwable was not caused by another throwable, or if the causative
 * throwable is unknown.  If this field is equal to this throwable itself,
 * it indicates that the cause of this throwable has not yet been
 * initialized.
 *
 * @serial
 * @since 1.4
 */
private Throwable cause = this;
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • 1
    This isnt quite the same though. In the OPs case the field was of type `Thing`, not of type `Object`. The Difference being one is explicitly always of the same type. – David says Reinstate Monica Jul 27 '15 at 16:45
  • @DavidGrinberg `Thing` or a sub-class of Thing. In any case it could be a linked list where the termination points to itself. Like Throwable does. – Peter Lawrey Jul 27 '15 at 16:49
  • 3
    @DavidGrinberg added Throwable as an example where the type of the field is the same as the class it is in. – Peter Lawrey Jul 27 '15 at 16:51
19

I can think of at least one example where it is justified. e.g.

I have a certificate chain where each link in the chain has a reference to its parent. At the top of the chain the last certificate is self signed so its parent is its self.

In short it really depends on the problem space you are modeling. Any absolute claims stating that this should not be done are suffering from a lack of imagination.

public class Cert {
    public Cert parent;
}

public class SelfSignedCert extends Cert {
    public SelfSignedCert() {
        this.parent = this;
    }
}
bhspencer
  • 13,086
  • 5
  • 35
  • 44
  • 4
    another example, I am my own barber:) – ZhongYu Jul 27 '15 at 20:06
  • @bayou.io btw, on [the barber paradox: *"the whole form of words is just noise without meaning."*](https://en.wikipedia.org/wiki/Barber_paradox) – jfs Jul 27 '15 at 23:55
  • The question says: "every instance of the class has itself as a field". In your example this would mean requiring _every_ certificate to be self-signed, which would clearly make the signature pointless. – Marc van Leeuwen Jul 28 '15 at 05:22
  • @MarcvanLeeuwen in the case there is a sub class called SelfSignedCert for which every instance has its self as a field. – bhspencer Jul 28 '15 at 11:52
11

No, in my opinion this is never justified, because every object implicitly already has such a field: this. Of course, it is justified for an object to have a field which may sometimes, but not always, refer to itself (which could for example occur in a cyclic linked list), but the question is about a field which always refers to the object itself.

I have seen code where such a field is used to be able to refer to the containing object from (anonymous) from inner classes, but also in that case this is not necessary. You can use ContainingClass.this. For example:

class A {
    class B {
        A getParent() {
            return A.this;
        }
    }
}
Hoopje
  • 12,677
  • 8
  • 34
  • 50
  • 2
    "this" does not work in anonymous inner classes. "this" would reference the anon cobject and not the holding parent object. – Jose Martinez Jul 27 '15 at 13:39
  • excellent. Going to try that out. Will it work on my example from my provided answer? – Jose Martinez Jul 27 '15 at 14:03
  • 2
    This answer is confusing, because it begins by stating that it is never justified, then in the following sentence present an example in which it is justified. Is is justified or not? If it is, then don't say it is never justified. – Anonymous Entity Jul 27 '15 at 15:53
  • 3
    @user11177 The answer quite clearly states that there are *no* justifications for a field which is *always* equal to `this`, but that there are *some* justifications for a field which is *sometimes* (but not always!) equal to `this`. Doesn't seem confusing at all to me... – fgp Jul 27 '15 at 21:51
6

Another example in JDK - java.lang.Throwable

private Throwable cause = this;

The cause field can be in 3 states - unset; set to null; set to another Throwable.

The implementer uses this to represent the unset state.

A more readable strategy is probably to define a sentinel value for unset

static Throwable UNSET = new Throwable();

private Throwable cause = UNSET;

of course, there's a recursive dependency - UNSET.cause=? - which is another fun topic.

ZhongYu
  • 19,446
  • 5
  • 33
  • 61
5

The only case I can think of is for some kinds of refactoring. To create an example, an object may have started out as a collection of static methods that are not very object-oriented:

public static void doItToIt(Foo it) {
  if (it.getType().equals("bar")) {
    it.setSomeVariable(value);
    it.manipulate();
  } else {
    // do nothing
  }
}

... so we decided to get rid of getType() and make it a subclass relationship, and when refactoring, the thing was copied and pasted so as to make the code cleaner and more object-oriented, necessitating:

public class Bar extends Foo {
    private Bar it = this;

    private String getType() {
      return "bar";
    }

    public void doItToIt() {
      if (it.getType().equals("bar")) {
        it.setSomeVariable(value);
        it.manipulate();
      } else {
        // do nothing
      }
    }
 }

If there were only one method like this, it'd be better to use a local variable:

public void doItToIt() {
  final Bar it = this;
  ...
}

but if there are several, using an instance variable would get the code working faster.

It would now be better to go and replace all instances of it with this (and get rid of getType(), and remove the if, and so forth) but as an intermediate step it's still an improvement, and it might get left in that state if there are (or are thought to be) other, more important things to do.

Another possibility would be copying pseudo-code from something like a specification in which this has a name in the pseudo-code and you are deliberately attempting to match the pseudo-code structure to make it easy to compare the implementation to the specification. (And, again, if you had multiple methods so using a local variable would lead to repetition.)

But generally speaking, no, having an instance variable that always refers to this is redundant and thus impedes clarity.

David P. Caldwell
  • 3,394
  • 1
  • 19
  • 32
  • The OP said "that's never used". So it may be a left over from this kind of refactoring, but the refactoring has been done in the mean time but the additional field not been removed yet. – Bodo Thiesen Jul 28 '15 at 05:49
5

It could be justified if the referenced object can be changed afterwards, but the initial value is this (although such a design should be revisited as well, because it may indicate that Thing has more responsibilities than it should).

However, if the referenced object is always this, then it is unnecessary and confusing.

The following declaration is not only confusing, but also funny :)

private final Thing thing = this;

Dragan Bozanovic
  • 23,102
  • 5
  • 43
  • 110
2

No because it would be redundant to have itself as a field when it has the keyword this

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." - Javadocs Keyword "this"

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
Huang Chen
  • 1,177
  • 9
  • 24
2

In iOS, objects quite often have delegates - typically another object that may supply data, or may do other things needed to make an object to work properly, as an alternative to subclassing. If an object implements all the functionality itself that the delegate should implement, then the object can be its own delegate. Not totally common, but not uncommon either.

Let's say you have a "boss" who has a "secretary", a "coffee maker" and a "driver". The boss can obviously write his own letters, make his own coffee and drive himself, but not every boss does. So sometimes one or more of these fields will be set to "this".

gnasher729
  • 51,477
  • 5
  • 75
  • 98
0

Case of Reflection with library UI controls.

It is fully legitimate in certain usage patterns. In undisclosed enterprise framework I've seen XML like this simplified example:

<form>
    <comboBox listItems="order.LineItems" displayMember="description" valueMember="selfRef"/>
</form>

Bindings of the control to values are made though Reflection. If you are happy with only Integer ID as valueMember, you do not need class member referencing to object itself. But if you want reference to object itself AND by design, empty value ("") isn't implemented as special case meaning this, then you need to keep this in a member variable (selfRef in the above example).

miroxlav
  • 11,796
  • 5
  • 58
  • 99