Reputation: 887
In Java, I see a lot of libraries lately that have classes with methods that always return the instance of the class so you can can call multiple methods without needing separate lines of code. For example:
public class Resource{
public Resource path(String path)
//execute some code
return this;
}
So you can do things like this
new Resource.path("1").path("2").path("3")
Rather than the verbose:
public void path(String path)
Resource r = new Resource();
r.path("1");
r.path("2");
r.path("3");
Is there a name to this pattern and is it good/bad practice?
Upvotes: 2
Views: 137
Reputation: 184
It's called fluent interface pattern.
Often applied in builder pattern aka fluent builder.
http://www.martinfowler.com/bliki/FluentInterface.html
As to second part of the question:
Pros:
Cons:
For more: http://en.wikipedia.org/wiki/Fluent_interface
The are probably some more aspects I didn't cover though
Upvotes: 10