Null Check increasing cyclic complexity

I have a java POJO class as shown below.

 public class EmployeeVo {
        private String firstName;
        private String middleName;
        private String lastName;
        private String suffix;
        private String addressline1;
        private String addressline2;
        private String city;
        private String state;
        private String zipCode;
        private String country;

            public String getFirstName() {
            return firstName;
        }
        public void setFirstName(String firstName) {
            this.firstName = firstName;
        }
        public String getMiddleName() {
            return middleName;
        }
        public void setMiddleName(String middleName) {
            this.middleName = middleName;
        }
        public String getLastName() {
            return lastName;
        }
        .// Setters and getters for other fields.
        .
        .

        }

Is there a way to check all fields of an object at once for null, and not check each field for null?

When retrieving these values ​​from an EmployeeVo object

public static boolean isEmpty(String string){
    if(null==string || string.trim().length()==0){
        return true;
    }
    return false;
}

I need to manually check each field before using it anywhere. Since the above object has more than 10 fields, it will obviously increase Cyclomatic Complexity for this method. Is there an optimal solution for him?

if(CommonUtil.isNotEmpty(employeeVO.getCity())){
            postalAddress.setCity(employeeVO.getCity());
        }
        if(CommonUtil.isNotEmpty(employeeVO.getCity())){
            postalAddress.setState(employeeVO.getState());
        }
        if(CommonUtil.isNotEmpty(employeeVO.getZipCode())){
            postalAddress.setPostalCode(employeeVO.getZipCode());
        }
        if(CommonUtil.isNotEmpty(employeeVO.getCountry())){
            postalAddress.setCountryCode(employeeVO.getCountry());
        }

Can i use

String country=employeeVO.getCountry();
postalAddress.setCountryCode( (country!=null) ? country: "");

Just to reduce complexity? Does it meet the standards?

+4
source share
2 answers

, , , .

, , .

, ,

+4

CC. .

String country=employeeVO.getCountry();
postalAddress.setCountryCode( (country!=null) ? country: "");

.

ifNotBlank(String input, String output);

, . , . , , .

        postalAddress.setCity(ifNotBlank(employeeVO.getCity(), ""));
        postalAddress.setState(ifNotBlank(employeeVO.getState(), ""));
        postalAddress.setPostalCode(ifNotBlank(employeeVO.getZipCode(), ""));
        postalAddress.setCountryCode(ifNotBlank(employeeVO.getCountry(), ""));

ifNotBlank .

import org.apache.commons.lang3.StringUtils;

public class ComplexityUtils{

    public static String ifNotBlank(String input, String output){
        return StringUtils.isBlank(input) ? output : input;
    }

}
+1

Source: https://habr.com/ru/post/1615238/


All Articles