How to reduce cyclomatic complexity?

后端 未结 2 1416
你的背包
你的背包 2021-02-01 16:31

I\'m working on a class which sends a RequestDTO to a Web Service. I need to validate the request before it is sent.

The request can be sent from 3 different places and

2条回答
  •  误落风尘
    2021-02-01 17:14

    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.

提交回复
热议问题