Related
So far from I have been searching through the net, the statement always have if and else condition such as a ? b : c. I would like to know whether the if ternary statement can be used without else.
Assuming i have the following code, i wish to close the PreparedStatement if it is not null
(I am using Java programming language.)
PreparedStatement pstmt;
//....
(pstmt!=null) ? pstmt.close : <do nothing>;
No, you cannot do that.
Instead try this:
if(bool1 && bool2) voidFunc1();
Why using ternary operator when you have only one choice?
if (pstmt != null) pstmt.close();
is enough!
Just write it out?
if(pstmt != null) pstmt.close();
It's the exact same length.
As mentioned in the other answers, you can't use a ternary operator to do this.
However, if the need strikes you, you can use Java 8 Optional and lambdas to put this kind of logic into a single statement:
Optional.of(pstmt).ifPresent((p) -> p.close())
Ternary if operator is the particular ternary operator. One of a kind.
From Wiki:
In mathematics, a ternary operation is an n-ary operation with n = 3.
It means all 3 operands are required for you.
A ternary operation is called ternary beacause it takes 3 arguments, if it takes 2 it is a binary operation.
And as noted above, it is an expression returning a value.
If you omit the else you would have an undefined situation where the expression would not return a value.
So as also noted in other answer, you should use an if statement.
You cannot use ternary without else, but to do a "if-without-else" in one line, you can use Java 8 Optional class.
PreparedStatement pstmt;
//....
Optional.ofNullable(pstmt).ifPresent(pstmt::close); // <- but IOException will still happen here. Handle it.
use:
<logic Expression> ? <method> : null;
Example:
(pstmt!=null) ? pstmt.close : null;
is dirty solution but works...
pstmt != null && pstmt.close;
The line of code above translates to When the left side of the expression "translates" to true -> execute the right side.
Well in JavaScript you can simply do:
expression ? doAction() : undefined
since that's what's literally actually happening in a real if statement, the else clause is simply undefined. I image you can do pretty much the same thing in (almost?) any programming language, for the else clause just put a null-type variable that doesn't return a value, it shouldn't cause any compile errors.
or just make a function to return if all else fails
function oy(x1,x2){if(x1) return x2();}
oy(etzem==6, ()=>yichoyliss=8);
I have run the PMD plugin in Eclipse against my code and I'm getting a high priority warning for code similar to the one shown below:
if(singleRequest !=null){
// do my work
}else{
// do my other work
}
PMD says `Avoid if (x != y) ..; else ..;
And the description of the error looks like this:
In an "if" expression with an "else" clause, avoid negation in
the test. For example, rephrase:
if (x != y) diff(); else same();
as:
if (x == y) same(); else diff();
Most "if (x != y)" cases without an "else" are often return
but I still can't understand the impact on my code. If someone could guide me with an example, I would appreciate it.
A number of PMD rules are more style opinions than correctness alerts. If you don't agree with this rule or the rule doesn't match your project's coding standards, you could consider suppressing warnings or even configuring PMD to enforce only the rules you like
PMD is a tool. PMD works based on heuristics. Someone decided upon this heuristic; that negative conditionals with else statements are not "good style".
However, in this case, as I have argued in my comments, the code posted is how I would write it. (In particular with x != null, but not exclusively to this construct.)
This is because I don't look at the conditional (excepting as it can be simplified; e.g. removing double-negatives as shown by Jim Kin) but rather I look at the logic of the branches or "flow".
That is, I place the positive branch first. In this case I contend that
if (x != null) {
doValid // positive branch
} else {
doFallback
}
is semantically equivalent to
if (isValid(x)) { // it looks like a "positive conditional" now
doValid // still positive branch
} else {
doFallback
}
and is thus positive branch first.
Of course, not all situations have such a "clear" positive flow, and some expressions might be expressed much easier in a negative manner. In these cases I will "invert" the branches - similar to what PMD is suggesting - usually with a comment stating the action at the top of the block if the positive branch/flow was reversed.
Another factor that may influence the conditional choice used is "immediate scope exiting" branches like:
if (x == null) {
// return, break, or
throw new Exception("oops!");
} else {
// But in this case, the else is silly
// and should be removed for clarity (IMOHO) which,
// if done, avoids the PMD warning entirely
}
This is how I consistently (a few occasional exceptions aside) write my code: if (x != null) { .. }. Use the tools available; and make them work for you. See Steven's answer for how PMD can be configured to a more suitable "taste" here.
It's a readability issue. Consider
if ( x != y )
{
}
else // "if x doesn't not equal y"
{
}
vs.
if ( x == y )
{
}
else // "if x doesn't equal y"
{
}
The latter example is more immediately identifiable. Mind you, I see nothing wrong with using negatives... it can make a lot more sense, consider
if ( x != null )...
The only reason I would avoid using the negative-case is if it resulted in double-negatives, which might be confusing.
e.g.
if (!checkbox.disabled) {
// checkbox is enabled
}
else {
// checkbox is disabled
}
Who reads your code? You do. The compiler does. Or maybe the assistant of the lecturer. A co-worker, who can't make difference between == and != ? Hope not.
I can only think negatives being bad in complex expressions. (Context being: at least for me. I know I've frustrated in debugging in my head while(!expr && !expr2 || expr3) { })
ch=getch(); if (ch!='a') is a pattern that is easily extended to
if (ch!='a' || ch!='b') which is always true, while sounding semantically correct.
From performance standpoint, it's best to sort the probabilities.
if (more_probable) {
....
unconditional_jump_to_end_of_block;
} else {
...
}
This choice should lead to better performance, as the there is no mis-prediction penalty in the more probable branch.
if (p && p->next) evaluated from performance standpoint gives poor results.
You have to avoid having "not equals" in the if condition. This is because when someone else looks at your code, there is a real possibility that the person might ignore the != and might jump to wrong conclusion about the logic of your program.
For your case, you may have to interchange the if logic with else logic and change != to ==
It's a balancing case of code readability vs. code organization. The warning is basically suggesting that it's confusing for people reading the code to navigate the negation of a negative.
My personal rule of thumb is, whatever you expect to be the "normal" case is what you should test for in the if. Consider:
if (x != y) {
// do work here...
} else {
throw new IllegalArgumentException();
}
In this situation I'd say that the important work is being done in the x != y case, so that's what you should test for. This is because I like to organize code so that the important work comes first, followed by handling for exceptional cases.
It's because "good style" says that if possible tests should be "positive", so:
if (singleRequest == null){
// do my other work
} else {
// do my work
}
Is easier to read because the test is "positive" (ie "equals" not "not equals"), and ultimately better readability leads to less bugs.
Edited
This is particularly the case with test like:
if (!str.equals("foo")) {
you can easily miss the ! at the front, but if you make the test positive, it's a lot cleaner.
The only time you should have a negative test is when there's no else block - then a negative test is unavoidable unless you have an empty true block, which itself is considered a style problem.
Not really an answer, but you can minimise the overall complexity and improve readability by returning or failing early and then continuing without indentation:
if (something == null) {
throw new IllegalArgumentException("something must not be null");
}
// continue here
Suppose I have an IF condition :
if (A || B)
∧
|
|
left
{
// do something
}
Now suppose that A is more likely to receive a true value then B , why do I care which one is on the left ?
If I put both of them in the IF brackets , then I know (as the programmer of the code) that both parties are needed .
The thing is , that my professor wrote on his lecture notes that I should put the "more likely variable to receive a true" on the left .
Can someone please explain the benefit ? okay , I put it on the left ... what am I gaining ? run time ?
Its not just about choosing the most likely condition on the left. You can also have a safe guard on the left meaning you can only have one order. Consider
if (s == null || s.length() == 0) // if the String is null or empty.
You can't swap the order here as the first condition protects the second from throwing an NPE.
Similarly you can have
if (s != null && s.length() > 0) // if the String is not empty
The reason for choosing the most likely to be true for || or false for && is a micro-optimisation, to avoid the cost of evaluated in the second expression. Whether this translates to a measurable performance difference is debatable.
I put it on the left ... what am I gaining ? run time ?
Because || operator in C++ uses short-circuit evaluation.
i.e: B is evaulated only if A is evaluated to a false.
However, note that in C++ short-circuit evaluation is guaranteed for "built in" data types and not custom data types.
As per javadoc
The && and || operators perform Conditional-AND and Conditional-OR operations on two boolean expressions. These operators exhibit "short-circuiting" behavior, which means that the second operand is evaluated only if needed
So, if true statement comes first in the order, it short-circuits the second operand at runtime.
If the expression on the left is true, there is no need to evaluate the expression on the right, and so it can be optimized out at run time. This is a technique called short-circuiting. So by placing the expression more likely to be true on the left, we can expect our program to perform better than if it were the other way around.
You should place the condition that is more likely to be true first because that will cause the if statement to short-circuit. Meaning it will not evaluate the rest of the if statement because it will already know the answer is true. This makes code more efficient.
This is especially useful when your if statement is evaluating expensive things:
if(doExpensiveCheck1() || doExpensiveCheck2()) { }
In this case cause the checks are expensive it is in your benefit to place the most likely check first.
In many cases there is no practical difference apart from a tiny performance improvement. Where this becomes useful is if your checks are very expensive function calls (unlikely) or you need to check things in order. Say for example you want to check a property on something and to check if that something is nil first, you might do something like:
If (a != nil && a.attribute == valid)
{}
Yes exactly, you're gaining runtime, it won't seem much for one operation, but you have to keep in mind that operations will get repeated millions of times
Why perform two evaluations when one is enough is the logic
At runtime if(a||b) will test a first, if a is true it will not waste time testing b therefor the compiler will be 1 execution ahead. Therefore if a is more likely to be true than b this test is also likely to cut 1 line. The total number of lines not executed is tiny on a single line but it’s huge if the statement is nested in a loop of some sort(for,while ,recession or database related queries ). Eg per say we have 1million mins to test data in a database at 1 minute per record (30sec for condition A and 30 sec for condition B). Let A have 80% chances to be true and B have 20% chances to be true. The total time needed if you put A first is 600-000hrs yet it’s 900-000hrs if you put B first.if A is tested first[(0,8*1millions hours)*0,5mins+(0,2*1million hours)*1min]===6000-000hrs : if B is tested first [(0,2*1million hours)*0,5mins+(0,2*1million hours)*1min]===9000-000hrs. However you will notice the difference is less significant if the probability of A becoming true is closer to that of B.
public class Main
{
public static void main(String[] args) {
System.out.println("Hello World");
Integer a = null;
Integer b = 3;
Integer c = 5;
if(a != null && a == 2){
System.out.println("both");
}else{
System.out.println("false");
}
}
}
Hello World
false
I'm trying to return a different value using a simple if/else to check for an even number in Java.
if (move % 2 == 0) {
return "o";
} else {
return "O";
}
I know in JavaScript you can use
if () : a ? b ;
Can this be used in Java?
Yes, you can use the ternary operator in Java:
return (move % 2 == 0) ? "o" : "O";
Just don't expect it to be any faster than the if-else.
Yes, you can use the conditional operator in Java:
return (move % 2 == 0) ? "o": "O";
It won't make your program any faster, but it's a little more concise and if you are familiar with the conditional operator, you will probably find it easier to read.
But conversely, if you don't know this operator it will be hard to guess what the code does.
Yes you can. It's called a ternary operator
Usage:
true ? case1 : case2; // returns case1
false ? case1 : case2; // returns case2
Instead of "optimizing" the if versus the ternary operator ? you should focus on the move % 2 == 0. If move is an integer and not a floating point variable this may be faster:
if( move & 1 == 0 )
return "E";
else
return "O";
Bit operations are usually faster than division or modulo calculations.
(conditional) ? if-true-statement : if-false-statement;
Yes it can, check out the Wikipedia page for Ternary Operators
There's no way you can use an if-statement in a more or less efficient way.
... and further more - keep in mind that, and this does not only apply for if-statements:
You should never try to optimize expressions used, for performance reasons - write code that focuses on readability (and in term, maintainability). The reason for this is that there's a JIT (Just-in-time compiler) that will optimize the bytecode, and modify the instructions you've specified in your byte-code.
If you're thinking about using the ternary operator, then consider, will this lead to harder to understand code (if you're multiple people working on the code). If it's just you working on the code then do as you please - and yes:
Object var = boolean-expression ? some-value : another-value;
is much more compact than:
Object var;
if (boolean-expression)
var = some-value;
else
var = another-value;
If you really need this to be blindingly fast, which is pretty dubious, you should also consider a lookup table:
static final char[] moveChar = {"o", "O"};
// ...
return moveChar[move % 2];
But I wouldn't implement any of the suggestions given here without timing them, and I wouldn't do anything at all until it had been proven that what you have now is really a bottleneck, by which I mean that it consumes more than about 50% of the CPU time.
Is it bad to write:
if (b == false) //...
while (b != true) //...
Is it always better to instead write:
if (!b) //...
while (!b) //...
Presumably there is no difference in performance (or is there?), but how do you weigh the explicitness, the conciseness, the clarity, the readability, etc between the two?
Update
To limit the subjectivity, I'd also appreciate any quotes from authoritative coding style guidelines over which is always preferable or which to use when.
Note: the variable name b is just used as an example, ala foo and bar.
It's not necessarily bad, it's just superfluous. Also, the actual variable name weights a lot. I would prefer for example if (userIsAllowedToLogin) over if (b) or even worse if (flag).
As to the performance concern, the compiler optimizes it away at any way.
As to the authoritative sources, I can't find something explicitly in the Java Code Conventions as originally written by Sun, but at least Checkstyle has a SimplifyBooleanExpression module which would warn about that.
You should not use the first style. I have seen people use:
if ( b == true )
if ( b == false )
I personally find it hard to read but it is passable. However, a big problem I have with that style is that it leads to the incredibly counter-intuitive examples you showed:
if ( b != true )
if ( b != false )
That takes more effort on the part of the reader to determine the authors intent. Personally, I find including an explicit comparison to true or false to be redundant and thus harder to read, but that's me.
This is strongly a matter of taste.
Personally I've found that if (!a) { is a lot less readable (EDIT: to me) than if (a == false) { and hence more error prone when maintaining the code later, and I've converted to use the latter form.
Basically I dislike the choice of symbols for logic operations instead of words (C versus Pascal), because to me a = 10 and not b = 20 reads easier than a == 10 && !(b==20), but that is the way it is in Java.
Anybody who puts the "== false" approach down in favour of "!" clearly never had stared at code for too long and missed that exclamation mark. Yes you can get code-blind.
The overriding reason why you shouldn't use the first style is because both of these are valid:
if (b = false) //...
while (b = true) //...
That is, if you accidentally leave out one character, you create an assignment instead of a comparison. An assignment expression evaluates to the value that was assigned, so the first statement above assigns the value false to b and evaluates to false. The second assigns true to b, so it always evaluates to true, no matter what you do with b inside the loop.
I've never seen the former except in code written by beginners; it's always the latter, and I don't think anyone is really confused by it. On the other hand, I think
int x;
...
if(x) //...
vs
if(x != 0) //...
is much more debatable, and in that case I do prefer the second
IMHO, I think if you just make the bool variable names prepended with "Is", it will be self evident and more meaningful and then, you can remove the explicit comparison with true or false
Example:
isEdited // use IsEdited in case of property names
isAuthorized // use IsAuthorized in case of property names
etc
I prefer the first, because it's clearer. The machine can read either equally well, but I try to write code for other people to read, not just the machine.
In my opinion it is simply annoying. Not something I would cause a ruckus over though.
The normal guideline is to never test against boolean. Some argue that the additional verbosity adds to clarity. The added code may help some people, but every reader will need to read more code.
This morning, I have lost 1/2 hour to find a bug. The code was
if ( !strcmp(runway_in_use,"CLOSED") == IPAS_FALSE)
printf(" ACTIVE FALSE \n"); else
printf(" ACTIVE TRUE \n");
If it was coded with normal convention, I would have seen a lot faster that it was wrong:
if (strcmp(runway_in_use, "CLOSED"))
printf(" ACTIVE FALSE \n"); else
printf(" ACTIVE TRUE \n");
I prefer the long approach, but I compare using == instead of != 99% of time.
I know this question is about Java, but I often switch between languages, and in C#, for instance, comparing with (for isntance) == false can help when dealing with nullable bool types. So I got this habbit of comparing with true or false but using the == operator.
I do these:
if(isSomething == false) or if(isSomething == true)
but I hate these:
if(isSomething != false) or if(isSomething != true)
for obvious readability reasons!
As long as you keep your code readable, it will not matter.
Personally, I would refactor the code so I am not using a negative test. for example.
if (b == false) {
// false
} else {
// true
}
or
boolean b = false;
while(b == false) {
if (condition)
b = true;
}
IMHO, In 90% of cases, code can be refactored so the negative test is not required.
This is my first answer on StackOverflow so be nice...
Recently while refactoring I noticed that 2 blocks of code had almost the exact same code but one used had
for (Alert alert : alerts) {
Long currentId = alert.getUserId();
if (vipList.contains(currentId)) {
customersToNotify.add(alert);
if (customersToNotify.size() == maxAlerts) {
break;
}
}
}
and the other had
for (Alert alert : alerts) {
Long currentId = alert.getUserId();
if (!vipList.contains(currentId)) {
customersToNotify.add(alert);
if (customersToNotify.size() == maxAlerts) {
break;
}
}
}
so in this case it made sense to create a method which worked for both conditions like this using boolean == condition to flip the meaning
private void appendCustomersToNotify(List<Alert> alerts
List<Alert> customersToNotify, List<Long> vipList, boolean vip){
for (Alert alert : alerts) {
Long currentId = alertItem.getUserId();
if (vip == vipList.contains(currentId)) {
customersToNotify.add(alertItem);
if (customersToNotify.size() == maxAlerts) {
break;
}
}
}
}
I would say it is bad.
while (!b) {
// do something
}
reads much better than
while (b != true) {
// do something
}
One of the reasons the first one (b==false) is frowned upon is that beginners often do not realize that the second alternative (!b) is possible at all. So using the first form may point at a misconception with boolean expressions and boolean variables. This way, using the second form has become some kind of a sjiboleth: when someone writes this, he/she probably understands what's going on.
I believe that this has caused the difference to be considered more important than it really is.
While both are valid, to me the first feels like a type error.
To me b == false looks as wrong as (i == 0) == false. It is like: huh?
Booleans are not an enum with 2 possible values. You don't compare them. Boolean are predicates and represent some truth. They have specific operators like &, |, ^, !.
To reverse the truth of an expression use the operator '!', pronounch it as "not".
With proper naming, it becomes natural: !isEmpty reads "not is empty", quite readable to me.
While isEmpty == false reads something like "it is false that it is empty", which I need more time to process.
I won't go into all of the details at length because many people have already answered correctly.
Functionality-wise, it gives the same result.
As far as styling goes, it's a matter of preference, but I do believe !condition to be more readable.
For the performance argument, I have seen many say that it makes no difference, but they have nothing to justify their claims. Let's go just a bit deeper into that one. So what happens when you compare them?
First, logically:
if(condition == false)
In this case, if is comparing its desired value to execute with the value between the parentheses, which has to be computed.
if(!condition)
In this case, if is directly compared to the opposite(NOT) of the condition. So instead of 2 comparisons, it is one comparison and 1 NOT operation, which is faster.
I wouldn't just say this without having tested it of course. Here is a quick screenshot of the test I did. !condition is nearly twice as fast over 10 million iterations.
https://imgur.com/a/jrPVKMw
EDIT: I tested this in C#, compiled with visual studio. Some compilers may be smarter and optimize it properly, which would make the performance the same.