Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calling java method one after each other with "dots" in between

Tags:

java

I see the following code syntax. Calling

ConfigurationBuilder cb = new ConfigurationBuilder();

cb.setDebugEnabled(true)
  .setOAuthConsumerKey("x11")
  .setOAuthConsumerSecret("x33")
  .setOAuthAccessToken("x55")
  .setOAuthAccessTokenSecret("x66");

All the methods after each other without using the object instance. How does this work in programming my own class when i want to use this kind of calling methods?

like image 358
user1120753 Avatar asked Dec 29 '11 08:12

user1120753


2 Answers

make each of those methods return the same object which they are called on:

class MyClass{
    public MyClass f(){
        //do stuff
        return this;
    }
}

It's a pretty common pattern. Have you ever seen this in C++?

int number=654;
cout<<"this string and a number: "<<number<<endl;

each call of the operator << returns the same ostream that is passed as its argument, so in this case cout, and since this operation is done left to right, it correctly prints the number after the string.

like image 107
Lorenzo Pistone Avatar answered Sep 30 '22 06:09

Lorenzo Pistone


That style of writing code is called 'fluent' and it is equivalent to this:

cb.setDebugEnabled(true);
cb.setOAuthConsumerKey("x11");
cb.setOAuthConsumerSecret("x33");
cb.setOAuthAccessToken("x55");
cb.setOAuthAccessTokenSecret("x66");

Each method returns 'this' in order to accommodate this style.

If you use this style, be prepared to encounter some inconvenience while debugging your code, because if you want to single-step into only one of those methods instead of each and every single one of them, the debugger might not necessarily give you the option to do that.

like image 38
Mike Nakis Avatar answered Sep 30 '22 08:09

Mike Nakis