5

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?

user1120753
  • 639
  • 6
  • 14

3 Answers3

8

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.

Lorenzo Pistone
  • 5,028
  • 3
  • 34
  • 65
  • I still can't wrap my head around this... Could you give us a better example? If I gave you a github link could you show me what it would look like when done using custom objects? – Cardinal System Apr 17 '17 at 19:15
3

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.

Mike Nakis
  • 56,297
  • 11
  • 110
  • 142
0

This is simmilar to a Builder design pattern.

Here you can find a excellent example of it inspired by Josh Bloch's code from Effective Java 2nd ed.

Community
  • 1
  • 1
Wojciech Owczarczyk
  • 5,595
  • 2
  • 33
  • 55
  • I do not think this is an instance of the builder design pattern. As a matter of fact, I do not think this is a design pattern at all. It is just a cute smart-ass way of writing code. – Mike Nakis Dec 29 '11 at 08:46
  • Yep, but builder pattern takes advantage of this cute smart-ass way of code-writing. – Wojciech Owczarczyk Dec 29 '11 at 08:48