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

4.1k views Asked by At

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.

1

There are 1 answers

2
agabrys On BEST ANSWER

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