I have the following lines in my code:
if (command.equals("sort") && args.length == 2) {
//run some program
}
Someone suggests that I should use two separate if statements because there's no need to evaluate any of the other if statements if the command does not equal to "sort", regardless of whether or not the args length is correct.
So according to that that, I need to rewrite my code to:
if (command.equals("sort")) {
if (args.length == 2) {
//run some program
}
}
I know they both do the job, but my question is which one is better and more efficient?
No, that's not true. They call it short circuit, if the first condition evaluates as false, the second one would not be evaluated at all.
Well, since && is a short-circuit operator. So both the if statements are effectively the same.
So, in first case, if your command.equals("sort"), returns false, the following condition will not be evaluated at all. So, in my opinion, just go with the first one. It's clearer.
As stated, short circuit will cause the program to exit the if statement the moment a condition fails, meaning any further conditions will not be evaluated, so there's no real difference in the way the two formats are evaluated.
I would like to note that code legibility is negatively affected when you have several if statements nested within each other, and that to me is the main reason not to nest. For example:
if( conditionA && conditionaB && !conditionC ){
// Do Something
}
is much cleaner than:
if( conditionA ){
if( conditionB ){
if( !conditionC ){
// Do Something
}
}
}
Imagine that with 20 nested if statements? Not a common occurrence, sure, but possible.
They are the same. For your first example, any modern runtime will ignore the second expression if the first expression is false.
short circuiting is better which is done by && if you are check null case for a value and then apply a function on that object, short circuit operator works well. It stops from condition 2 to be executed if condition 1 is false.
ex:
String s=null;
if(s!=null && s.length())
This doesnt throw exceptions and also in most cases you save one more if check.
If the conditions are in the same order, they are exactly the same in terms of efficient.
if (command.equals("sort") && args.length == 2)
Will drop out if command.squals("sort") returns false and args.length will never be checked. That's the short-circuit operation of the && operator.
What it comes down to is a matter of style and readability. IMO When you start chaining too many together in a single if statement it can get hard to read.
Actually, it is called [Lazy_evaluation]: http://en.wikipedia.org/wiki/Lazy_evaluation
That's not really the question but note that if you want the two if evaluated, you can use & :
if (methodA() & methodB()) {
//
}
instead of
boolean a = methodA();
boolean b = methodB();
if (a && b) {
//
}
yeah, their suggestions are completely right. What I suggest you is to write the first check as:
"sort".equals(command)
Maybe it does not make sense in this case but in future. Use the static type first so you never need a null check before
Related
I am developing in Java and I am using IntelliJ as my IDE. I wrote an if statement as follows.
if( list1.size() >= 1 || list2.contains(itemX) ) {
//do something
}
IntelliJ suggested a transformation (DeMorgan's Law) and it transformed it to:
if( ! ( list1.size() < 1 && !( list2.contains(itemX) ) ) ) {
//do something
}
So it applied a very common discrete mathematics theory on simplifying boolean expressions. What I am wondering is how does this optimize anything?
|| operator anyways does not execute the whole condition if the first part is itself true, and only executes the RHS only if the first part is false.
Is the transformed condition effective? How?
This is somewhat subjective, but a good general rule of thumb is to remove as much complexity as possible. By complexity, I mean the number of operations you need to perform in order to obtain the desired result.
In this sense, !a && !b is worse than !(a || b) because in one case you're negating a and b, then performing the OR and operator resulting in 3 operations whereas in the latter case, you're only performing 2. Of course this is vacuous when you're talking about two conditions, but when you're dealing with many, this can make a big difference.
But in your scenario it doesn't make any sense for your IDE to change it as the later has lower number of operations. Probably its the IDE trying to desperately woo you :)
Hope this makes sense !!
Both are exactly the same statements.
I agree that OR operator does not evaluate the second part if the first part is TRUE, however, it is also true that the AND operator does not evaluate the second part if the first part is FALSE.
In fact, it will take more time and space to evaluate the ~(~A && ~B) as opposed to A||B.
Hope this helps :)
Are there logically any difference between
if (name.startsWith("a"){
return true;
} else if (name.startsWith("b") {
return true;
} else if (name.startsWith("c") {
return true;
}
and
if(name.startsWith("a") || name.startsWith("b") || name.startsWith("c") ){
return true;
}
I prefer the second one as it is elegant to me. I'd like to understand "are there any differences?"
They're the same.
The second one is definitely easier to read, and readability is incredibly important in programming.
The rule I like to go by is that if multiple branches of an if-else statement produce the same behavior, I combine them. (Be sure that they're the EXACT same behavior)
In this case: no.
Boolean expressions with || and && use short-circuiting, which means that B is ignored in A || B if A already evaluated to true. Therefore, the first alternative is not more efficient.
If the body of the if clause gets bigger though, and contains the same code, then you absolutely don't want to use the first version:
if (name.startsWith("a"){
// lots of code
} else if (name.startsWith("b") {
// lost of the same code
}
Code duplication is a terrible sin and often the cause for annoying bugs.
They're equivalent, but the second one is preferable as it's more concise - you'd use the first one if the different conditions should be handled differently, e.g.
if(name.startsWith("a")) {
System.out.println("first side effect");
return true;
} else if (name.startsWith("b")) {
System.out.println("a different side effect");
return true;
}
Both will do the stuff.
And The last and the best one. i.e LOGICAL OR
if(name.startsWith("a") || name.startsWith("b"){
etc...
}
Because in logical ||
In this case It's just short-circuiting.
in which the second argument is only executed or evaluated if the first argument does not suffice to determine the value of the expression:
They are logically identical. The second one is certainly more elegant and concise though.
Of course, neither snippet of code will work because you have forgotten closing braces. :)
No difference in this case. They're equivalent.
Which of these would be correct?
if(dialog != null && dialog.isShowing){}
if(dialog.isShowing && dialog != null){}
if(dialog != null){
if(dialog.isShowing){}
}
The first and third ones are both OK to use because they won't process past the null check. The second one can result in a NullPointerException because it's referencing dialog before you've checked if it's null.
The && operator in Java will stop evaluating (from left to right) as soon as it encounters a false. Therefore in
if(dialog != null && dialog.isShowing){}
dialog.isShowing() will not be called if the dialog is null and is therefore "safe" to use.
This:
if(dialog != null){
if(dialog.isShowing){}
}
will work as well, but generally nesting if-statements like this is avoided as it decreases readability.
Even though everything has been answered, for the sake of completeness:
The way Java evaluates conditional clauses is called Short circuit evaluation. This means that once the result of the condition is asserted, further clauses will not be evaluated.
Edit: My statement is not completely true actually. Java uses Short circuit evaluation when using || and && (which is the standard what every programmer uses, thus my statement in the first place), but you may force Java to evaluate all statements by using & and |
The && operator is called a short circuit operator. This means once the result is known. i.e., false && x is always false it doesn't evaluate the remaining expressions.
A variation on this is using the || short circuit, OR operation, like:
if(text == null || text.isEmpty())
It's shortcut logic. When first expression is false, Java will not check second expression, because whole expression is false definity.
First case is best practice.
Second case is incorrect.
You may use try and catch if you want to use the second one otherwise the first and the third one are correct.
For my work I have to develop a small Java application that parses very large XML files (~300k lines) to select very specific data (using Pattern), so I'm trying to optimize it a little. I was wondering what was better between these 2 snippets:
if (boolean_condition && matcher.find(string)) {
...
}
OR
if (boolean_condition) {
if (matcher.find(string)) {
...
}
}
Other details:
These if statements are executed on each iteration inside a loop (~20k iterations)
The boolean_condition is a boolean calculated on each iteration using an external function
If the boolean is set to false, I don't need to test the regular expression for matches
Thanks for your help.
One golden rule I follow is to "Avoid Nesting" as much as I can. But if it is at the cost of making my single if condition too complex, I don't mind nesting it out.
Besides you're using the short-circuit && operator. So if the boolean is false, it won't even try matching!
So,
if (boolean_condition && matcher.find(string)) {
...
}
is the way to go!
The following two methods:
public void oneIf(boolean a, boolean b)
{
if (a && b)
{
}
}
public void twoIfs(boolean a, boolean b)
{
if (a)
{
if (b)
{
}
}
}
produce the exact same byte code for the method body so there won't be any performance difference meaning it is purely a stylistic matter which you use (personally I prefer the first style).
Both ways are OK, and the second condition won't be tested if the first one is false.
Use the one that makes the code the more readable and understandable. For just two conditions, the first way is more logical and readable. It might not be the case anymore with 5 or 6 conditions linked with &&, || and !.
I recommend extracting your expression to a semantically meaningful variable and then passing that to your evaluation. Instead of:
if (boolean_condition && matcher.find(string)) { ... }
Assign the expression to a variable, then evaluate the variable:
const hasItem = boolean_condition && matcher.find(string)
if (hasItem) { ... }
With this method, you can keep even the most complex evaluations readable:
const hasItem = boolean_condition && matcher.find(string)
const hasOtherThing = boolean_condition || boolean_condition
const isBeforeToday = new Date(string) < new Date()
if (hasItem && hasOtherThing && isBeforeToday) { ... }
Java uses short-circuiting for those boolean operators, so both variations are functionally identical. Therefore, if the boolean_condition is false, it will not continue on to the matching
Ultimately, it comes down to which you find easier to read and debug, but deep nesting can become unwieldy if you end up with a massive amount of braces at the end
One way you can improve the readability, should the condition become longer is to simply split it onto multiple lines:
if(boolean_condition &&
matcher.find(string))
{
...
}
The only choice at that point is whether to put the && and || at the end of the previous line, or the start of the current.
I tend to see too many && and || strung together into a logic soup and are often the source of subtle bugs.
It is too easy to just add another && or || to what you think is the right spot and break existing logic.
Because of this as a general rule i try not to use either of them to avoid the temptation of adding more as requirements change.
If you like to be compliant to Sonar rule squid:S1066 you should collapse if statements to avoid warning since it states:
Collapsible "if" statements should be merged
The first one. I try to avoid if nesting like that, i think it's poor style/ugly code and the && will shortcircuit and only test with matcher.find() if the boolean is true.
In terms of performance, they're the same.
But even if they weren't
what's almost certain to dominate the time in this code is matcher.find(string) because it's a function call.
Most would prefer to use the below one, because of "&&".
if (boolean_condition && matcher.find(string)) {
...
}
We normally called these as "short-circuit (or minimum evaluation)". It means the 2nd argument (here it is "matcher.find(string)") is only evaluated only if the 1st argument doesn't have sufficient information to determine the value of the expression. As an example, if the "boolean_condition" is false, then the overall condition must be false (because of here logical AND operator). Then compiler won't check the 2nd argument which will cause to reduce the running time of your code.
I have such code:
if(object != null && object.field != null){
object.field = "foo";
}
Assume that object is null.
Does this code result in nullPointerException or just if statement won't be executed?
If it does, how to refactor this code to be more elegant (if it is possible of course)?
&& does short circuit while & would not.
But with simple questions like this, it is best to just try it (ideone can help when you don't have access to a machine).
&& - http://ideone.com/LvV6w
& - http://ideone.com/X5PdU
Finally the place to check for sure would be the JLS §15.23. Not the most easy thing to read, the relevent section states:
The && operator is like & (§15.22.2), but evaluates its right-hand operand only if the value of its left-hand operand is true.
Java does have short circuit evaluation, i.e. your code should be ok
One way to know it! Test it! How? Well, make a method which prints out something:
public static boolean test(int i)
{
System.out.println(i);
return false;
}
...
if (test(1) && test(2) && test(3))
{
// not reached
}
This prints:
1
So the answer on your question is "no".
Best way to find out would be try it, especially for a single line question. Would have been faster, too.
The answer is that Java will not execute the body of the "if".
This will not throw any NullPointerException . The condition will be evaluated from left to right and the moment first false expression is found it will not evaluate remaining expression.
Maybe this other question helps you:
Differences in boolean operators: & vs && and | vs ||
Java has short circuit evaluation, so it will be fine.
The code looks ok to me, but do you actually need to check object.field != null? I think that test can be omitted as you never use the variable, just set it.
On a side-note, most programmers wouldn't access fields directly (object.field) but rather through getters/setters (object.setField(x);). Without any more context to go on, I can't say if this is appropriate in your case.
&& and || conditions stops at the point they can decide whether the condition is true/false, in your case, the condition will stop right after object != null and I think that your code is just fine for this case
If you want all of your boolean expressions evaluated regardless of the truth value of each, then you can use & and | instead of && and ||. However make sure you use these only on boolean expressions. Unlike && and ||, & and | also have a meaning for numeric types which is completely different from their meaning for booleans.
http://ibiblio.org/java/course/week2/46.html
Although short circuiting would work here, its not a guarantee that (like I have done many times) you'll get the order wrong when writing another, it would be better practice to nest those if statements and define the order you want the boolean checks to break:
if(object != null)
{
if(object.field != null)
{
object.field = "foo";
}
}
This does exactly the same as you're essentially saying, if the first boolean check fails don't do the second; it is also nullPointerException safe as object.field will not be checked unless object is not null
Using short-circuiting on booleans can become annoying later on as when you have a multiple bool if statement it becomes trickier to efficiently debug which part short circuited.