Is Confusing ternary Rule in Sonar Qube really needed? - java

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.
e.g.
if(reporters username is not oliver)
say it's stackoverflow's concern
else
say it's oliver's concern

Related

Avoid Literals In If Condition SonarQube error

I am getting error like Avoid Literals In If Condition in sonarqube , and unable to find the proper solution to it.
SingleWrapper singleWrapper=null;
:
:
singleWrapper=createWrapper();
:
private void wrap(){
if(singleWrapper != null){ //Here i am getting error.
//do Something
}
}
I know this question seems to be repeated one but its not,because previously asked for String .
Thanks for any help.
It is because your static code analysis tool detects null as a hardcoded literal, which, rigorously, is true.
The recommended behavior is to declare a constant object like
final static Object NULL = null;
and use it like
if(singleWrapper != NULL)
But I haven't still met a developer doing this. In this case, I think you're OK and you can ignore the code check warnings. That's my 2 cents.
The description for the PMD rule reads:
Avoid using hard coded literals in conditional statements, declare those as static variables or private members.
While in most cases it is relevant (you don't want to have arbitrary hard coded string or numerical literals), in this case it is (IMHO) a bit too zealous, for checking against null is so widely used that it should probably be ignored by this rule.
Since this rule comes from PMD (not SQ internal engine), you could ask for an upstream fix - or just remove it from your profile if it really bugs you.
Note that this rule is part of the Controversial Rules set.

Ternary Operators Java [duplicate]

This question already has answers here:
Ternary Operator
(4 answers)
Closed 5 months ago.
Is there a way to implement this in a ternary operation. I'm very new to that ternary stuff, maybe you could guide me.
if(selection.toLowerCase().equals("produkt"))
cmdCse.setVisible(true);
else
cmdCse.setVisible(false);
This one doesn't seem to work.
selection.toLowerCase().equals("produkt")?cmdCse.setVisible(true):cmdCse.setVisible(false);
In this case, you don't even need a ternary operator:
cmdCse.setVisible(selection.toLowerCase().equals("produkt"));
Or, cleaner:
cmdCse.setVisible(selection.equalsIgnoreCase("produkt"));
Your version:
selection.toLowerCase().equals("produkt")? cmdCse.setVisible(true): cmdCse.setVisible(false);
is semantically incorrect: ternary operator should represent alternative assignments, it's not a full replacement for if statements. This is ok:
double wow = x > y? Math.sqrt(y): x;
because you are assigning either x or Math.sqrt(y) to wow, depending on a condition.
My 2cents: use ternary operator only when it makes your program clearer, otherwise you will end up having some undecipherable one-liners.
Perhaps
cmdCse.setVisible(selection.toLowerCase().equals("produkt"));
The ternary operator isn't exactly like an if statement. A ternary operator has to "return" something from both sides, so putting void method calls like setVisible() there won't work.
Instead, you could do something like this without ternary operators at all:
cmdCse.setVisible(selection.toLowerCase().equals("product"));
But just to demonstrate the point, the ternary equivalent would look something like this:
cmdCse.setVisible(selection.toLowerCase().equals("product") ? true : false);
Notice how now the ternary operator "returns" true or false on both sides instead of simply calling a void method.
I think this will work for you
cmdCse.setVisible(selection.toLowerCase().equals("produkt"));
Directly from the docs
Use the ?: operator instead of an if-then-else statement if it makes your code more readable; for example, when the expressions are compact and without side-effects (such as assignments).
In your case cmdCse.setVisible(true / false); doesn't return anything, and the operation also has side effects (it changes state of cmdCse), so the conditional operator cannot be used here (when you do use the operator, both of the ? and : branches must have the same return type).
As an aside, please note that .. ? .. : .. should be referred to as the conditional operator
On the issue of using exceptions
I want to answer the issue of the exceptions here as this question is a duplicate for another question concerning throwing exceptions from a ternary expression, but this is not addressed in the above answers.
The general consensus is that it cannot be done directly as in:
public Character next() {
return hasNext() ? s.charAt(cur++) : throw new NoSuchElementException(); // compilation error
}
will give you a compilation error, but as Clement pointed out it can be done via a declared extra function. It can also be done via (ab-)using lambda expressions.
public Character next() {
return hasNext() ? s.charAt(cur++) : ((Function<Integer, Character>) x -> {throw new NoSuchElementException();}).apply(1);
}
for sure this is not that pretty (it is pretty ugly) and I would not recommend to do that for readability purposes, but sometimes there are circumstances which might warrant exceptionally doing that. If someones figures out a way to do it without the cast it would be a bit more readable.
If you had a function throwNoSuchElementException() defined somewhere that you use more than once, it would look a bit more readable:
public Character next() {
return hasNext() ? s.charAt(cur++) : throwNoSuchElementException();
}
(P.S.: I included this answer for completeness sake, as I asked myself can it really be not done?)
(P.S.S.: If the exception to be thrown is not a runtime exception this will not work so easily and would require even more handstands - not really worth it)
Here are my tips, if you need to set things to booleans, then simple use setBoolean(condition), else, if you need to set a variable to a non boolean value, then use var=condition?result1:result2(or the variable itself if you don't want to change if condition is false), otherwise, use if else.

Which is faster "If (bool) {true} else {false}" or "bool ? true : false"? Why? In every languages? [duplicate]

This question already has answers here:
Is the ternary operator faster than an "if" condition in Java [duplicate]
(9 answers)
Closed 9 years ago.
This is something I was thinking, when I searched at Google I couldn't find the answer (maybe I don't know the keywords). Just at a curiosity level, no implementation in any project.
Which is faster:
if (bool)
return true;
else
return false;
or
bool ? true : false;
Are they equal?
Why?
One is faster than another in every language, in every system?
(If someone knows the answer for microcontrollers, Obj-C for iOS or Java, I would really appreciate your answer to my question)
EDIT:
I didn't know that bool ? true : false is called ternary, as I said "I don't know the keywords".
This Question has a number of problems.
First, languages don't have performance characteristics. You cannot measure the performance of a language. You can only measure an implementation of a language. And any given language can have lots of different implementations.
The idea that all languages will support constructs equivalent to those two is naive ... and incorrect.
The idea that something might perform the same way across all languages and all implementations and all systems, is fanciful.
The idea that anyone would know ... for all languages, platforms, hardware, etcetera is fanciful.
It is unclear what those two utterances mean. In Java (for example) they don't mean the same thing ... the second one is not a valid statement ... even if you add a ; ... and even if it was, it doesn't return anything.
Having said that ... in Java (assuming you add a return in the 2nd case):
they mean the same thing, and
a modern Hotspot JIT compiler is likely to compile those to equivalent native code; i.e. there is likely to be no performance difference.
In Java, at least, there's no difference between them other than the ability to debug line-by-line in the first case. The compiled bytecode is most likely exactly the same for both cases. I suspect the same is true in every environment you are asking about.
The speed difference occurs at the machine code level, and at that level it can't even be guessed which of your idioms compiled into it. Therefore your answer is: there is no correlation between the choice of your idioms and performance. Mostly it should be exactly the same, but if it isn't, there will be no generally applicable explanation.
What is usually faster is
return bool;
This avoids any possible branching produced by the conditional, being faster on a CPU with expensive branch misses. An optimizing compiler might remove the branch anyway, but since this is language agnostic it can't be guaranteed.
The conditional expression versus the ternary is debatable. This is one of those ones where you shouldn't be able to notice a difference in either case.
If you have a single if/else (which that should be, there is no need for an else if in there), the Ternary will be faster.
However, it is more difficult to add additional checks, since you need to chain the ternary:
(conditional) ? ((conditional) ? true : false) : ((conditional) ? true : false) so it becomes difficult to read.
The best choice if expansion is possible is to use a switch which is faster than an if/else check. This is especially true if you want to allow multiple if's to result in the same result, but is not useful if you're using datatype checking since it uses loose comparisons (== and never === checks). Unlike an if/elseif/else pair, the switch can potentially use more memory and time if you never break.
Performance wise both Ternary and if-else are same.
Ternary operators are just shorthand. They compile into the equivalent if-else statement.
Are they equal?
Logically yes. The do the same thing here. The second one is called ternary operator.
One is faster than another in every language, in every system?
In java there is no difference. I doubt if there is any performance in other language also. Even if so, then I guess the difference will be very negligible. You better concentrate on more readable codes. The first one is definitely more readable.
They are pretty much equal in performance, or if not there is a very, VERY trivial difference.
For something simple like what you asked for I would use the ternary operator ?: because it is much shorter and still very readable.
When you need to do multiple statements, use if-else.
Remember that you can also use ?: in return statements:
return bool ? yes : no;
EDIT: It looks like you just want to return the value of the boolean. If you do then all you have to type is: return bool;

Which has better performance: test != null or null != test [duplicate]

This question already has answers here:
object==null or null==object?
(11 answers)
Closed 2 years ago.
Consider the following two lines of code
if (test ! = null)
and
if (null != test)
Is there is any difference in above two statements, performance wise? I have seen many people using the later and when questioned they say its a best practice with no solid reason.
No difference.
Second one is merely because C/C++ where programmers always did assignment instead of comparing.
E.g.
// no compiler complaint at all for C/C++
// while in Java, this is illegal.
if(a = 2) {
}
// this is illegal in C/C++
// and thus become best practice, from C/C++ which is not applicable to Java at all.
if(2 = a) {
}
While java compiler will generate compilation error.
So I personally prefer first one because of readability, people tend to read from left to right, which read as if test is not equal to null instead of null is not equal to test.
They are exactly the same. The second one can make sense when using equals:
if("bla".equals(test))
can never throw a NullPointerException whereas:
if(test.equals("bla"))
can.
There is no performance difference but I personally find the second one being confusing.
Second one looks for me like "Yoda condition", i.e. if(2 == x) ... and is much less readable.
It's best practice to avoid some basic typo's that most modern IDE's will pick up, because sometimes you want to do comparisons between more complex types that are not null and end up doing accidental assignments. So the pattern remains the same, but I've never seen this linked to performance and have never seen it generate special byte code.
The idea is to have the static, known value first, so you can't throw any kind of weird exception when you perform the comparison.
Neither of the two methods are "more correct" though, so it's entirely up to you to decide what you wish to use.
there is no difference. But in second way you avoid the typo like test = null. Beacause in second way you'll get compiler error.
It's not a best practice to use the latter one. Both are equivalent, but the former is easier to read.
This "best practice" comes from C where boolean don't exist. Integers are used instead, and if (foo = 1) is not a syntax error, but is completely different from if (foo == 1).
In Java, only boolean expressions can be inside an if, and this practice doesn't make much sense.
There is no really different between two form. There is no performance issue but there are following notes:
First form is readable for code reader, because people usually read codes Left-To-Right.
Second form is better for code writer, because in java = operator is for assignment and == operator is for test equivalent, but people usually using in if statement = instead of ==, by second approch developer getting Compile-Time-Error because null can't use in Left-Side of a assignment statement.

Is "else if" one whole or two separate keywords in Java?

I happen to read the practicing material for SCJP certification, and I just tripped over a chapter of flow control et al, where they give the impression that "else if" is a keyword on its own. I have always thought that it was just a normal else, containing nothing but an if block, braces omitted.
So, which is it?
Edit: I'd like to emphasize that this question is more in the "pique my interest" category than the "serious business" one.
Yes, they are two separate keywords—the Java language specification does not specify an else if keyword. It is actually, as the other posters here have said, an if statement contained inside of an else statement.
EDIT: A lot of training/educational materials seem to imply that else if is actually a keyword (and, indeed, it is usually treated as such), but I am inclined to think that this is more for the sake of clarity/simplicity, with the consequence of sacrificing accuracy.
it would be two separate keywords indicated by the space between the two words.
It actually says
else {
if { ... }
}
It's two keywords.
else may be followed by a block or a single statement.
in the case of else if. The statement is another if statement.
Update
It wouldn't hurt to mention that else if is a common style choice for deeply nested if statements and makes this situation much more readable than nesting. Unless I need the fall-through behaviour possible with the switch statement, I use else if instead.
Two separate keywords I believe. But i'm positive you cannot have an else without an if.
Java Lexical Structure
While some languages do have 'elsif', 'elseif', or 'else if' as a separate statement (somewhat like a 'case' statement), Java is not one of them.
I'm no Java expert, but in C it's certainly defined as two different keywords, and Java stole pretty liberally from that part of C's syntax.
Regardless, outside of silly questions on exams, it won't ever make a difference in practice. The effect is identical either way.
If you open your assembly with a debugger you'd recognise its an "if" statement.

Categories

Resources