mardi 26 mai 2020

Java - Reduce Cyclomatic Complexity

Is there a way I could refactor my code? I have here a validation method that checks if the following attribute is correct. But since my request/RuleAttribute has so many attributes it triggers a sonarqube issue. Sonarqube is only allowing 10.

Note that I have another method named validateSecondAttributes, similar to this one that checks for attributes 3-4. It also triggers the cyclomatic complexity issue on sonarqube.

Here is my code below:

    protected String validateAttributes(RuleAttributes attributes,
                                    boolean isForSimpleFieldComparison) {

    String error = StringUtils.EMPTY;

    if (StringUtils.isBlank(attributes.getEntityField1())) {
        error = "Rule Validation: entityField1 not defined.";
    } else if (StringUtils.isBlank(attributes.getSourceField1())) {
        error = "Rule Validation: sourceField1 not defined.";
    } else if (StringUtils.isBlank(attributes.getEntityField2())) {
        error = "Rule Validation: entityField2 not defined.";
    } else if (StringUtils.isBlank(attributes.getSourceField2())) {
        error = "Rule Validation: sourceField2 not defined.";
    } else if (attributes.getPrefixLength1() < 0) {
        error = "Rule Validation: prefixLength1 must not be less than 0.";
    } else if (attributes.getSuffixLength1() < 0) {
        error = "Rule Validation: suffixLength1 must not be less than 0.";
    } else if (attributes.getPrefixLength2() < 0) {
        error = "Rule Validation: prefixLength2 must not be less than 0.";
    } else if (attributes.getSuffixLength2() < 0) {
        error = "Rule Validation: suffixLength2 must not be less than 0.";
    } else if (isOperatorInvalid(attributes.getOperator())) {
        error =
            MessageFormat.format("Rule Validation: {0} is not a valid operator value.", attributes.getOperator());
    } else if (StringUtils.isNotBlank(attributes.getDataSourceMapping1())
        && StringUtils.isBlank(attributes.getDataSourceMapping2())) {
        error = "Rule Validation: dataSourceMapping2 not defined.";
    } else if (StringUtils.isBlank(attributes.getDataSourceMapping1())
        && StringUtils.isNotBlank(attributes.getDataSourceMapping2())) {
        error = "Rule Validation: dataSourceMapping1 not defined.";
    } else if (StringUtils.isBlank(attributes.getRuleInput())) {
        error = "Rule Validation: ruleInput must not be blank.";
    } else if (hasInvalidRuleInput(attributes.getRuleInput())) {
        error = String.format(
            "Rule Validation: ruleInput value is not valid. Value must be %1$s or %2$s. No ruleInput attribute defined defaults to %1$s.",
            Constants.HIERARCHICAL_CARTESIAN_PRODUCT, Constants.NON_HIERARCHICAL_CARTESIAN_PRODUCT);
    }

    error = validateCombinationOperatorAttribute(attributes, isForSimpleFieldComparison, error);

    return error;
}

Aucun commentaire:

Enregistrer un commentaire