I thought about how to handle objects created in JavaBeans in the method chain.
I don't know if it's the exact specification, but the common JavaBeans specifications are as follows.
There are many other things, but the important one is this one. Click here for official specifications → JavaBeans Spec
HogeBean.java
public class HogeBean {
private String name;
private String id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
Like this. With lombok
HogeBean.java
@Data
public class HogeBean {
private String name;
private String id;
}
This is OK.
For example, suppose you have a HogeBean and a FugaBean with similar fields.
HogeBean.java
@Data
public class HogeBean {
private String name;
private String id;
}
FugaBean.java
@Data
public class FugaBean {
private String id;
private String password;
}
If you want to convert HogeBean to FugaBean in Stream, think normally
List<HogeBean> hoges = ...
hoges.stream().map(hoge -> {
FugaBean fuga = new FugaBean();
fuga.setId(hoge.getId());
return fuga;
}).Termination
I will write only like this. It's not so beautiful.
It may not be very beautiful, but the curly braces + return in the map is a preventable pattern.
hoges.stream().map(hoge -> new FugaBean(){
{
setId(hoge.getId());
}
}).Termination
It's much cleaner than before. But there are drawbacks
The option to quit JavaBeans. Modify the setter as follows.
FugaBean.java
public HogeBean setId(String id) {
this.id = id;
return this;
}
For lombok, just add Accessors (chain = true)
FugaBean.java
@Data
@Accessors(chain = true)
The processing of the case can be done as follows
hoges.stream().map(hoge -> new FugaBean().setId(hoge.getId())).Termination
Refreshing. But after all there are drawbacks,
Like this
BeanCreater.java
public final class BeanCreater<T> {
private BeanCreater() {
}
private T bean;
public static <T> BeanCreater<T> of(Supplier<T> supplier) {
BeanCreater<T> builder = new BeanCreater<T>();
builder.bean = supplier.get();
return builder;
}
public BeanCreater<T> construct(Consumer<T> consumer) {
consumer.accept(this.bean);
return this;
}
public T build() {
return this.bean;
}
}
With this,
hoges.stream().map(hoge -> BeanCreater.of(FugaBean::new)
.construct(bean -> bean.setId(hoge.getId())).build()).Termination
Hmm. I tried it, but it's not good enough. The code is too noisy.
Personally, I like Solution 2 the most. It has a flowing interface, and there is no waste in essence and ritual talk. I hope JavaBeans will be more flexible considering the current situation. (I don't think that's the case ...) Click here for the BeanCreater created this time https://github.com/7tsuno/BeanCreater
Please advise if you have any other ideas!
Recommended Posts