How to reduce cyclomatic complexity?

An easy way is to promote the check into a separate method:

private String getAppendString(String value, String appendString) {
    if (value == null || value.isEmpty()) {
        return "";
    }
    return appendString;
}

And then you can use this method instead of the if blocks:

sb.append(getAppendString(request.getStreet(), "street,");

This will reduce complexity from 28 down to 3. Always remember: high complexity counts are an indication that a method is trying to do too much. Complexity can be dealt with by dividing the problem into smaller pieces, like we did here.

Leave a Comment

tech