There is a class which has many fields and all of them are required. The java code is like:
public class MyCls {
private String aaa;
private String bbb;
private String ccc;
private String ddd;
private String eee;
private String fff;
private String ggg;
public MyCls(String aaa, String bbb, String ccc, String ddd, String eee, String fff, String ggg) {
this.aaa = aaa;
this.bbb = bbb;
this.ccc = ccc;
this.ddd = ddd;
this.eee = eee;
this.fff = fff;
this.ggg = ggg;
}
// here are getters for all fields, no setters
}
The caller code will be:
new MyCls("111","222","333","444","555","666","777");
My friend said it's not easy to find the meaning of each parameter, so create a builder for it. This is the code:
package builder;
public class MyClsBuilder {
private String aaa;
private String bbb;
private String ccc;
private String ddd;
private String eee;
private String fff;
private String ggg;
public MyClsBuilder setAaa(String aaa) {
this.aaa = aaa;
return this;
}
// similar code for 'bbb','ccc',...,'ggg'
public MyClsBuilder setGgg(String ggg) {
this.ggg = ggg;
return this;
}
public MyCls createMyCls() {
return new MyCls(aaa, bbb, ccc, ddd, eee, fff, ggg);
}
}
The caller code will be:
MyCls cls = new MyClsBuilder()
.setAaa("111").setBbb("222").setCcc("333")
.setDdd("444").setEee("555").setFff("666").setGgg("777")
.createMyCls();
Ok, we can see what setter we used for each parameter, it's clearer. But I have a question:
Do we really need such a builder? I can't see much benefit.
In fact, if we add setters for the original code, we can write similar code without creating a new class:
MyCls cls = new MyClsBuilder();
cls.setAaa("111");
cls.setBbb("222");
cls.setCcc("333");
cls.setDdd("444");
cls.setEee("555");
cls.setFff("666");
cls.setGgg("777");
The only difference is is's not a chain.
And to use that MyClsBuilder
, I have to worry about if I forget to call any setX
by mistaken.
MyCls cls = new MyClsBuilder()
.setAaa("111").setBbb("222").setCcc("333")
.setDdd("444").setEee("555").setFff("666")
.createMyCls();
// forget to invoke `.setGgg("777")`
But with the "constructor" one, there is no such problem since the compiler will check it for me.
So I don't think a builder a good solution, is it any better one?