java - 三元运算符不能嵌套(squid :S3358) be configured

标签 java sonarqube sonarlint sonarlint-eclipse

当我有以下具有 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 在处理代码约定时如此严格?

我不想ignore规则,只是自定义以允许最多 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?

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

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

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

关于java - 三元运算符不能嵌套(squid :S3358) be configured,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53369046/

相关文章:

java - 使用 GridBagLayout JTables 和 JScrollPane 不起作用

java - SonarQube 因 java.lang.StackOverflowError 失败 - 如何确定导致错误的特定文件

java - XML 解析器不应容易受到 XXE 攻击。解决零影响的最佳方法?

java - 不应在数组实例上调用 "hashCode"和 "toString"(SonarLint)

intellij-idea - SonarLint Intellij 在连接模式下没有发现任何问题

java - servlet 中的资源注释触发 squid :S2226

java - Java 如何找出字符串中出现次数最多的字符?

java - 比较 kotlin 中的两个列表

java - 在 Wildfly 9 上部署 Spring Boot 应用

python - 如何使用 Django、Jenkins 和 Sonar 获得测试覆盖率?