简体   繁体   中英

Is Confusing ternary Rule in Sonar Qube really needed?

I write my java code

if(x !=null){
    // Do something
}
else {
    // Do something
}

Then sonar Qube gives violation. Is the rule really needed for Confusing ternary?

According to the reference link you provided, the rule states:

In a ternary expression avoid negation in the test. For example, rephrase: "(x != y) ? diff : same" as: "(x == y) ? same : diff". Consistent use of this rule makes the code easier to read. Also, this resolves trivial ordering problems, such as "does the error case go first?" or "does the common case go first?".

It might be a bit confusing that the rule is named "confusing ternary rule" because what you have is a regular if-else construct, not a ternary expression. However, since ?: can be thought of as shorthand for an if-else statement, you can also apply the rule here.

Does it makes sense? Personally, I think absolutely. But if it doesn't apply to your (or your company's) coding style and, therefore, you get many violations, I'd rather remove—or adapt—the rule. As the reference says: consistency is important.

This is required cause it's unnecessary causes confusion in first look.

eg

if(reporters username is not oliver)
   say it's stackoverflow's concern
else 
   say it's oliver's concern

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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