Currently I can think of only three good reasons to return this
in a (public) method, namely:
(mmyers) when implementing fluent interfaces, e.g.
public class X { ... public X enableValidation() { setValidation(true); return this; } ... }
(Jon Skeet) for identity conversions, e.g.
public class X { ... public X toX() { return this; } ... }
(Dave Ray) implementing a
clone()
orcopy()
method on an immutable object, e.g.@Immutable public class X { ... public X copy() { return this; } ... }
Are there any other useful scenarios in an object-oriented language in which you would return this
or self
from a method?