How to reduce cyclomatic complexity?

后端 未结 2 1374
你的背包
你的背包 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.

    0 讨论(0)
  • 2021-02-01 17:17

    Another approach would be to enforce that contract in the Request object itself. If a field is required or can't be null, say so when the Request is created.

    Create the Request in such a way that it's 100% valid and ready to go when the constructor exists.

    I'd also create that String version in the Request toString() method. It should know how to render itself.

    0 讨论(0)
提交回复
热议问题