When using a builder pattern, like Lombok’s @Builder
, you could have more than one ternary operator, but since they are all in the same “line of code”, it detects more than one and triggers the rule even when the ternaries aren’t immediately nested.
- What language is this for?
- Java
- Which rule?
- Ternary operators should not be nested
- Why do you believe it’s a false-positive/false-negative?
- In this specific case, the nesting doesn’t make it harder to read
- Are you using
- SonarCloud?
- No
- SonarQube - which version?
- Yes, 9.8
- SonarLint - which IDE/version?
- Yes v7.3.0.59206, on IntelliJ Ultimate v2022.3.1
- in connected mode with SonarQube or SonarCloud?
- Not in this particular project. I’ve noticed this issue through SonarLint, but didn’t test it on SonarQube yet.
- SonarCloud?
- How can we reproduce the problem? Give us a self-contained snippet (best) or screenshot (good)
var something = buildSomething();
var otherThing = FirstClass.builder()
.firstClassAttribute(something == null ? null : SecondClass.builder()
.secondClassAttribute1(something)
.secondClassAttribute2(something.isAnotherThing() ? RandomEnum.ENUM_VALUE_1 : RandomEnum.ENUM_VALUE_2)
.build())
.build();
In this case, something.isAnotherThing() ? RandomEnum.ENUM_VALUE_1 : RandomEnum.ENUM_VALUE_2
is triggering the nesting issue. This could be like 10 lines apart from the part in which it could create confusion. There is no confusion here in this code that could be caused by the ternary operators