代码改造实录--使用Builder替代setter,减少对象属性赋值的代码行数

原来的代码:

        Reply reply = new Reply();
        reply.setDoctorId(doctor.getId());
        reply.setPatientId(replayVo1.getPatientId());
        reply.setRealName(replayVo1.getRealName());
        reply.setReplyMsg(replayVo1.getReplyMsg());
        reply.setClassify("communication");
        reply.setPushStates(0);
        reply.setDate(DateUtils.getToday());

修改后代码:

        Reply reply = Reply.builder().doctorId(doctor.getId()).patientId(replayVo1.getPatientId())
            .realName(replayVo1.getRealName()).replyMsg(replayVo1.getReplyMsg()).classify("communication").pushStates(0)
            .date(DateUtils.getToday()).build();

项目中的Builder是用lombok的@Builder注解实现的,没有因此增加过多代码。这样修改,避免了代码里大篇幅用在set属性值上。当然,也可以用构造方法来达到此目的,只是在eclipse工具下各参数在方法中的位置不直观。

原文地址:https://www.cnblogs.com/GreenMountain/p/13392044.html