2

When I have the following code with 2 levels of Ternary operations

 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.

4
  • I am with Sonar on this. This should be changed to nested-if. Commented Nov 19, 2018 at 5:59
  • @Kartik I'm too, but there are opinions that reject it, can sonar be more flexible with this rule? Commented Nov 19, 2018 at 6:00
  • @Kartik I don't want to ignore, I want to customize, allow up to 2 levels instead of 1 Commented Nov 19, 2018 at 6:06
  • oh sorry then, no idea.. retracting the duplicate flag Commented Nov 19, 2018 at 6:08

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

how to disable this rule ? in sonarqube or sonarlint

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.