如何降低圈复杂度? [英] How to reduce cyclomatic complexity?

查看:804
本文介绍了如何降低圈复杂度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个将RequestDTO发送到Web服务的类。我需要在请求发送之前对其进行验证。

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

请求可以从3个不同的地方发送,并且每个请求类型都有不同的验证规则,例如: request1必须有姓名和phonenumber,request2必须有地址等)

The request can be sent from 3 different places and there are different validation rules for each "requesttype", e.g. request1 must have name and phonenumber, request2 must have address, etc)

我有一个DTO,其中包含一长串字段(姓名,地址,城市,电话号码等) 。)并且无论是哪种类型的请求都是相同的DTO。

I have a DTO which contains a long list of fields (name, address, city, phonenumber, etc.) and it is the same DTO sent no matter which type of request it is.

我创建了3种不同的验证方法,并根据类型调用了适当的方法。

I have created 3 different validation methods and based on the type the appropriate method is called.

在每种方法中,我都有一长串if-else来检查每种请求类型所必需的字段。

In each of these methods I have a long list of if-else's to check for the fields that are necessary for each request type.

private void validateRequest1(Request request) {
    StringBuilder sb = new StringBuilder();
    if (null == request) {
        throw new IllegalArgumentException("Request is null");
    }
    if (isFieldEmpty(request.getName())) {  *see below
        sb.append("name,"));
    }
    if (isFieldEmpty(request.getStreet())) {
        sb.append("street,"));
    }
    ...

isFieldEmpty() 检查字符串是否为空, isEmpty()并返回一个布尔值

isFieldEmpty() checks the string for null and isEmpty() and returns a boolean

这给出了我在其中一种方法中的圈复杂度为28,所以我的问题是......是否有可能降低这种复杂性? - 如果是的话,我该怎么做呢?

This gives me a cyclomatic complexity of 28 in one of those methods so my question is.. is it possible to reduce this complexity? - if so, how would I go about doing so?

最后我需要查看很多字段,如果没有大量的检查我怎么看不出来: /

Ultimately I need to check a lot of fields and I cannot see how this can be done without lots of checks :/

推荐答案

一种简单的方法是将支票提升为单独的方法:

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

然后您可以使用此方法代替 if blocks:

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

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

这会将复杂性从28降低到3.永远记住:高复杂度计数是一个指示方法试图做得太多。复杂性可以通过将问题分成更小的部分来处理,就像我们在这里做的那样。

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.

这篇关于如何降低圈复杂度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆