简体   繁体   English

减少圈复杂度问题

[英]Reduce cyclomatic complexity issue

I have to fix sonar issue related to big cyclomatic complexity, but still haven't got any good idea how to do that. 我必须解决与较大的圈复杂度有关的声纳问题,但如何执行此操作尚无任何好主意。

The code consist of big amount of 'if' operators that are check parameters that came in method and decide which enum value to create 该代码由大量的“ if”运算符组成,这些运算符是检查方法中传入的参数并确定要创建的枚举值的方法

Here is a code snippet for example: 这是一个代码片段,例如:

      public ProductType createProductType(String val1, String val2, String val3) {
        if (PRODUCT_MODEL.equals(val1) && PRODUCT_TYPE.equals(val2) {
            return ProductType.SOAP;
        }
        if (PRODUCT_MODEL.equals(val1) || val3.equals(SWAP)) {
            return ProductType.STRING;
        }
}

And so on.. As you can see I am not able to write this using switch case because there are more than 1 variable is checked. 依此类推..如您所见,我无法使用switch case编写此代码,因为检查了多个变量。 Also I can't create static map with keys of Predicate type because comparing criteria came to method dynamically. 另外,我无法使用Predicate类型的键创建静态映射,因为比较条件是动态地比较到方法的。 So I can't understand how to eliminate this 'if' operators. 因此,我不明白如何消除此“ if”运算符。

Any suggestions? 有什么建议么?

EDIT 编辑

if divide it into methods for each product type how then I will check when the product type is created? 如果将每种产品类型分为不同的方法,那么我将如何检查产品类型的创建时间? I mean I have 我是说我有

ProductType productType = null;
productType = tryParseSoap;
if (Objects.nonNull(productType)) {
    return productType;
}
productType = tryParseString;
if (Objects.nonNull(productType)) {
    return productType
}

if do this I still have a lot of if cases for null-checking because without them suggest product created on the first check and then I will anyway check it a lot of times and this is a big productivity reducing 如果这样做,我仍然有很多if检查的情况,因为如果没有这种情况,则建议在第一次检查时创建产品,然后无论如何我都会对其进行很多次检查,这极大地降低了生产率

You could define an interface, say ProductTypeCreator 您可以定义一个接口,例如ProductTypeCreator

public interface ProductTypeCreator {

    boolean isApplicable(String val1, String val2, String val3);

    ProductType create(String val1, String val2, String val3);

}

Then, create an implementation for each specific if case. 然后,为每个特定的if案例创建一个实现。 You could then have a List creators, and refactor your method to something like. 然后,您可以拥有一个列表创建者,并将您的方法重构为类似的形式。

public ProductType createProductType(String val1, String val2, String val3) {
    // this should already be instantiated
    List<ProductTypeCreator> creators;
    return creators
       .stream()
       .filter(creator -> creator.isApplicable(val1, val2, val3))
       .map(creator -> creator.create(val1, val2, val3))
       .findFirst()
       .get();
}

In this way, you could avoid the ifs. 这样,您可以避免ifs。

Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM