java - Null Check 增加圈复杂度

标签 java string exception sonarqube cyclomatic-complexity

我有一个 java POJO 类,如下所示。

 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.
        .
        .

        }

有什么方法可以一次检查对象的所有字段是否为 null,而不是检查每个字段是否为 null?

从 EmployeeVo 对象中检索这些值时

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

在某些地方使用它之前,我必须手动对每个字段进行空检查。 由于上面的对象有超过 10 个字段,它显然会增加该方法的圈复杂度。 有什么最优解吗?

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());
        }

我们可以使用

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

只是为了降低复杂性?这符合标准吗?

最佳答案

决定是否设置一个字段不是调用者的责任,它应该是它自己的方法。

在您的情况下,这意味着 setter 必须决定是否设置参数的值。

这将一个方法的复杂性转移到了单个单独的方法上,因此降低了调用者的复杂性

关于java - Null Check 增加圈复杂度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33629502/

相关文章:

java - 我对 @ModelAttribute 的理解正确吗?

java - AES 128 DOT NET 和 Java 兼容性

Java 集合 ArrayList、LinkedList 抛出异常

string - 在 MATLAB 中将三个数字连接在一起

ruby 1.9 : how do I get a byte-index-based slice of a String?

Java : Concurrent Modification exception when replacing pattern in ArrayList

java - 如何使响应式@WebFilter与@RequestBody正常工作?

python - 如何在不使用 Python 库函数的情况下将字符串转换为整数?

haskell - 安静退出(无一异常(exception))haskell

c++ - C++ 是否已经有了某种反射?