Having chaining implemented on beans is very handy: no need for overloading constructors, mega constructors, factories, and gives you increased readability. I can't think of any downsides, unless you want your object to be immutable, in which case it would not have any setters anyway. So is there a reason why this isn't an OOP convention?
public class DTO {
private String foo;
private String bar;
public String getFoo() {
return foo;
}
public String getBar() {
return bar;
}
public DTO setFoo(String foo) {
this.foo = foo;
return this;
}
public DTO setBar(String bar) {
this.bar = bar;
return this;
}
}
//...//
DTO dto = new DTO().setFoo("foo").setBar("bar");
myCustomDTO = DTOBuilder.defaultDTO().withFoo("foo").withBar("bar").Build();
I'd do that, so as to not conflict with the general idea that setters are voids. – Feb 02 '16 at 23:21new Foo().setBar('bar').setBaz('baz')
feels very "fluent". I mean, sure it could be implemented exactly the same way, but I'd very much expect to read something more likeFoo().barsThe('bar').withThe('baz').andQuuxes('the quux')
– Wayne Werner Feb 03 '16 at 04:00prop = value
sort of syntax, which cannot chain. – Telastyn Feb 03 '16 at 12:56public class Foo<T extends Foo> {...}
with the setter returningFoo<T>
, that way Inheritance doesn't break the setters. Also those 'setter' methods, I also prefer to call them 'with' methods. If overloading works fine, then justFoo<T> with(Bar b) {...}
, otherwiseFoo<T> withBar(Bar b)
. – YoYo Feb 04 '16 at 09:57new X().setA().setB().setC();
in Java with a dummy class X, setA and setC returning X, and setB throwing an exception. The stack trace points to setB. In general, in a chain of function calls with one of them throwing an exception, I'd expect the stack trace to identify that as the 'leaf node' that threw the exception. – Lawrence Feb 04 '16 at 14:21SetFoo
. By definition, you’re changing the state of Foo… – Telastyn Feb 04 '23 at 23:22