Return this

In any object oriented language you can call methods on an object. In java you can call these methods using the dot syntax. An example would be:


You can also call methods on the return values of other methods using this method. Just assume that the method call is actually an object and use the dot syntax to call the method. For instance:


Sometimes though you may want to keep working on the same object over and over. Consider manipulating a string where every method makes changes to the object.

MyString someString = new MyString("la la la");
// someString is now "LaLaLa"

This seems fairly intuitive. Each method call changes the underlying object. If you wanted to keep the original, or you are using threads and you need to make sure that the object can not be manipulated at a later time, you could always call the .clone() method on the object.

Not cloning as a default makes the operations faster. Creating an object in java always takes a little time, so simply making the changes to the original object is faster. However you may be familiar with daisy chaining of methods calls for strings in java.


Strings in java accomplishes this by return a clone of the object. Slow, but useful. I’m here to tell you that if you don’t need the clone, you should consider returning this.

Returning this???

Yes. At the end of you method, instead of returning a new object. Just write “return this”. What you are doing now is returning the object you are working on.

class MyString{
    MyString someFancyOperation(){
            Do fancy stuff here...
        return this;
    MyString uselessMethod(){
            Do useless stuff here...
        return this;

Now we can call all our methods on the same object without having to clone.

MyString someString = new MyString("la la la");


  1. Jacob June 26, 2011

    Thanks for the post. That’s a very informative bit about java creating string clones to handle daisy chained. However, I find your final example confusing.

    To be clear, given your example MyString object, your final example daisy chain call still produces a clone, because you call:


    instead of:

    • hmottestad June 26, 2011

      How about now?

  2. Ruudjah June 26, 2011

    This technique is called fluent interfaces ( This technique has a problem in Java: polymorphism. Suppose you have an interface SomeInterface, with a getter/setter Name (getName, setName). In the setter, you’d require implementors to return the interface type. Now, when you write something like

    SomeInterface someInstance = new ConcreteClass().setName(“I has a name”);

    It works, because setName is part of the interface specification. ConcreteClass now has a getter/setter for amount, getAmount and setAmount. When constructing, you might want to also set the amount, so you’ll endup with

    SomeInterface someInstance = new ConcreteClass().setName(“I has a name”).setAmount(42);

    This won’t work, because amount is a property of the concrete class, not for the interface. You either have to not use polymorphism or ditch the fluent interface concept.

    • hmottestad June 26, 2011

      True. In some cases you would have to make a choice between polymorphism and fluent interfaces (btw, thanks for letting me know what it’s called).

    • Matt June 26, 2011

      You can still do this with concrete classes by adding a generic argument to your interface’s type that takes a subtype of itself:

      	interface FooFluent {
      		T setFoo(int foo);
      		T setBar(int bar);
      	class FooConcrete implements FooFluent {
      		public FooConcrete setFoo(int foo) {
      			return this;
      		public FooConcrete setBar(int bar) {
      			return this;
      • Matt June 26, 2011

        Formatting ate my generics:

        interface FooFluent<T extends FooFluent<T>> {
        class FooConcrete implements FooFluent<FooConcrete> {

      • Ruudjah June 26, 2011

        This solution I think is mainly going beyond the goal of fluent interfaces. You can find more solutions for this problem on the web, but the ‘fluent’ part then becomes not so fluent anymore. The syntactical additions you’d need for this to work properly are not worth the effort to maintain fluency in the code.

  3. Ross Bonner June 26, 2011

    The pattern you refer to is commonly known as a fluent interface, see …

  4. Paul Keeble June 26, 2011

    Cloning rarely costs enough to matter. But by cloning the object we ensure that multiple users of the object aren’t impacted by the changes. Strings being very much treated as values are an example of objects where changing them with clones makes far more sense, not because its the fastest implementation (although it can be) but because its much safer.

    Concurrency is here and being used. Immutability is a sure fire way to make your objects work properly under multiple threads.

    In a nuttshell the cost of cloning is normally so small you should ignore the performance impact and instead treat values as immutable. Life will be easier in the long run, they are certainly easier to debug than chains of modifiers.

  5. Hristo Deshev June 26, 2011

    Smalltalkers have been doing this for years (and actually that’s where the technique came from). I’d advise readers to play for a bit with that language. You’ll gain tons of insight about object-oriented programming and your Java will get better. A lot better.

    I hear Pharo is a cool and friendly Smalltalk implementation you can start with:

Comments are Disabled