Optimization in constructor parameters

丶灬走出姿态 提交于 2021-01-28 08:41:33

问题


I'm setting parameter directly into DTO which output we are getting from HQL

Below is the HQL:

@Query(value = "SELECT new com.test.vos.CustomerDetails(firstname, lastName, address1, address2, address3, id, companyName, companyAddress, otherDetails) "
            + "FROM MstCustomer mc "
            + "INNER JOIN mc.mstAddress md "
            + "INNER JOIN mc.MstCompany mComapny "
            + "WHERE mc.mobileNo = :mobileNo ")
public List<CustomerDetails> getCustomerDetails(@Param("mobileNo") Integer mobileNo);

DTO :

public class CustomerDetails {
    private String firstName;
    private String lastName;
    private String address1;
    private String address2;
    private String address3;
    private String id;
    private String companyName;
    private String companyAddress;
    privatr String otherDetails;

    public CustomerDetails(String firstName, String lastName, String address1, String address2, String address3, String id, String companyName, String companyAddress, String otherDetails) {
        super();
        this.firstName = storeCode;
        this.lastName = lastName;
        this.address1 = address1;
        this.address2 = address2;
        this.address3 = address3;
        this.id = id;
        this.companyName = companyName;
        this.companyAddress = companyAddress;
        this.otherDetails = otherDetails;
    }

    // Getter and Setter
}

Above all code are working fine only issue is that its showing Constructor has 9 parameters, which is greater than 7 authorized.

How to resolved that warning? What would be best approach?


回答1:


Use a Builder pattern to get one parameter (builder) in constructor

 private CustomerDetails(CustomerDetailsBuilder builder) {
    // ... set all fields using builder
 public static class CustomerDetailsBuilder
    //...update all parameters and build method

This uses a additional class UserBuilder which helps us in building desired User object with all mandatory attributes and combination of optional attributes, without loosing the immutability.

For example

CustomerDetails customerDetails = new CustomerDetails.CustomerDetailsBuilder("Lokesh", "Gupta")
.address1("street 1")
.address2("Floor 2")
.address3("Fake address 1234")
.build();

Another option is lombok's @AllArgsConstructor

Generates an all-args constructor. An all-args constructor requires one argument for every field in the class.



来源:https://stackoverflow.com/questions/58060511/optimization-in-constructor-parameters

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!