Ternary operators when using a builder pattern and nested ternary trigger

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.
  • 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

Hello @bergamin,

Thanks for your message. I was able to reproduce the issue.

First of all, it would be nice of you if next time you can provide a proper compiling example so I don’t need to guess what are the missing parts. While in your case it’s obvious, it still takes some time to write them.

Actually, the issue is reported in your case because it’s indeed a Nested ternary operator. However, I can agree with you that it’s not nested in a bad way, and if we’re talking about a builder pattern it could be the way to go and it doesn’t decrease the readability. SO I created a ticket to improve the rule. Here it is:

https://sonarsource.atlassian.net/browse/SONARJAVA-4566

Regards,
Margarita

4 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.