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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With