可以配置不应该嵌套的三元运算符(鱿鱼:S3358)

Can Ternary operators should not be nested (squid:S3358) be configured

当我有以下带有 2 级三元运算的代码时

 double amount = isValid ? (isTypeA ? vo.getTypeA() : vo.getTypeB()) : 0;

Sonar 发出警告

Ternary operators should not be nested (squid:S3358)

Just because you can do something, doesn't mean you should, and that's the case with nested ternary operations. Nesting ternary operators results in the kind of code that may seem clear as day when you write it, but six months later will leave maintainers (or worse - future you) scratching their heads and cursing.

Instead, err on the side of clarity, and use another line to express the nested operation as a separate statement.

我的同事建议这样的水平可以接受,而且比替代方案更清晰。

我想知道是否可以将此规则(或其他规则)配置为允许的级别限制?

如果不是,为什么 sonar 在处理代码约定时如此严格?

我不想 规则,只是自定义允许最多 2 个级别而不是 1 个级别。

I wonder if this rule can be configured to allowed levels limit?

无法配置Ternary operators should not be nested规则。您只能启用或禁用它。

I wonder if other rules can be configured to allowed levels limit?

我不知道有任何现有规则可以做到这一点。幸运的是,您能够创建自定义分析器。原始规则 class 在这里 NestedTernaryOperatorsCheck。您可以简单地复制它并根据您的需要进行调整。

why sonar is so strict when it deals with code conventions?

SonarSource 为不同的语言提供了很多规则。每一次定制都会让代码更难维护。他们的能力有限,所以他们必须做出所有用户都不接受(但大多数人都接受)的决定。