Reputation: 16278
Does creating chainable methods make the execution poorly?
I'm talking about this:
public class Foo {
public Foo bar() {
// Code
return this;
}
public Foo setBar() {
// Code
return this;
}
}
Foo foo = new Foo();
foo.bar().setBar();
Is this better than creating a Foo.Builder
class and get the Foo
object with a Builder.getFoo();
method?
Upvotes: 1
Views: 582
Reputation: 31952
There are no efficiency concerns in regular java in doing this. The reason to go with a Builder
pattern (StringBuilder
), etc is because of the way your class functions (immutability of String
), which might make certain operations inefficient.
Upvotes: 1
Reputation: 77206
This sort of pattern, called a fluent interface makes the code much more readable. Unfortunately, the JavaBeans standard, which is very widely used, specifies that setters must have a void
return, and returning this
can break some tools that expect to match the exact signature. There's a good overview here.
Upvotes: 2