简体   繁体   English

不能嵌套三元运算符(squid:S3358)

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

When I have the following code with 2 levels of Ternary operations 当我有以下代码具有2级三元运算时

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

Which Sonar warns about 声纳警告的

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. 相反,为了清楚起见,请犯错,并使用另一行将嵌套操作表示为单独的语句。

My colleague suggested that such level can be accepted and it's more clear than the alternative. 我的同事建议可以接受这样的级别,并且比其他级别更清楚。

I wonder if this rule (or others) can be configured to allowed levels limit? 我想知道是否可以将此规则(或其他规则)配置为允许的级别限制?

If not, why sonar is so strict when it deals with code conventions? 如果不是,为什么声纳在处理代码约定时是如此严格?

I don't want to ignore rule, just to customize to allow up to 2 levels instead of 1. 我不想忽略规则,只是自定义以允许最多2个级别而不是1个级别。

I wonder if this rule can be configured to allowed levels limit? 我想知道是否可以将此规则配置为允许的级别限制?

The Ternary operators should not be nested rule cannot be configured. 三元运算符不应该嵌套不能配置规则。 You are only able to enable or disable it. 您只能启用或禁用它。

I wonder if other rules can be configured to allowed levels limit? 我想知道是否可以将其他规则配置为允许的级别限制?

I don't know any existing rule which can do it. 我不知道任何现有的规则都可以做到。 Luckily, you are able to create a custom analyzer. 幸运的是,您能够创建自定义分析器。 The original rule class is here NestedTernaryOperatorsCheck . 原始规则类在此处NestedTernaryOperatorsCheck You can simply copy it and adjust to your needs. 您可以简单地复制它并根据需要进行调整。

why sonar is so strict when it deals with code conventions? 为什么声纳在处理代码约定时是如此严格?

SonarSource provides a lot of rules for different languages. SonarSource为不同的语言提供了很多规则。 Every customization makes code more difficult to maintain. 每次定制都会使代码更难以维护。 They have a limited capacity, so they have to make decisions which are unaccepted by all users (but are accepted by most of them). 他们的能力有限,因此必须做出所有用户都不接受(但大多数用户都接受)的决策。

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

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