Rarely I bump into & and | logic operators in other's codes instead of || and &&. I made a quick research because I never used them and didn't know what is it for.
A && B means if A is false, B won't be evaluated and it will return false.
A & B means if A is false, B will be evaluated even if the form will return false as well.
Of course it is the same game with | and ||.
My question is: does it make sense anyways to evaluate the second member if the first determine the evaluation? I can imagine a code where the second member does something super important logic in clode and so it should be evaluated, but I suspect it is bad practice. Is it enough to make | and & exist?
from a comment, to make it more clear: I have the feeling that the program is not optimal and working well or better to say: designed well if all of the logical members HAS to be evaluated.
You forgot about bitwise operations
The bitwise & operator performs a bitwise AND operation.
The bitwise | operator performs a bitwise inclusive OR operation.
But here you can find example when unconditional AND operator is better:
What are the cases in which it is better to use unconditional AND (& instead of &&)
The single & and | are not logical operators, they're bitwise and logical operators.
You can use the | and & operators as you said above. Some static code analyzers will warn you because it might mask a possible problem. In those cases where you really want both conditions evaluated, you can do something like:
boolean cond1=cond1();
boolean cond2=cond2();
boolean myCond=cond1 && cond2;
if you just use
boolean myCond=cond1()&cond2();
someone is bound to "correct" it for you.
So yes, there are places where you would use & and |, but most likely it's not a good idea and you can get around it for the sake of clarity.
Imagine if B was a function that you wanted to execute all the time then it would be useful.
I think that might be quite good example:
if (initializeConnectionA() & initializeConnectionB() & initializeConnectionC()) {
performOperation();
} else {
logger.warn("Not all modules are working properly");
}
Where methods initializeConnection connects to i.e. some external servers that might not all be working. You might not require to initialize them all but you want to be warned if some of them are not working.
Of course it might not be the clearest solution for this problem, but this is example where & operator might be useful.
Related
Is there an option in Android Studio linter settings to make sure any occurrence of the boolean '&' operator causes an error and only allowing the '&&' operator (while still allowing the & operator for bit-wise operations on numbers)?
TL;DR: As you probably know, in Java the '&' operator evaluates both operands before it performs the AND operation, while the '&&' operator stops evaluating operands at the first operand evaluating to false.
I personally find this distinction both confusing and pointless. With the '&&' operator you can do things like:
if (a != null && fn (a)) { ... }
meaning that fn should never be called with a value of null. If I accidentally write:
if (a != null & fn (a)) { ... }
the whole test is completely meaningless. I want to ensure this kind of typo can never occur. A linter rule would be the perfect way to enforce this.
The linter rule should distinguish between the types of the operands. When & is used with numbers, its meaning is a bit-wise and operator. I do not want to disallow this, of course, as it's quite useful. Moreover, the OR operators | and || behave in a similar way, and I want to disallow | for booleans while allowing it for numerical operations. So basically:
int a = (3 & 4); // OK
boolean b = (true && false); // OK
boolean c = (true & false); // linter error, hopefully
int d = (5 | 7); // OK
boolean e = (true || false); // OK
boolean f = (true | false); // linter error, hopefully
Is there an option in Android Studio linter settings to make sure any occurrence of the boolean '&' operator causes an error and only allowing the '&&' operator?
The short answer is "no."
You can always write your own lint rules (see here for a sample), but this is not a default option in IntelliJ.
This isn't a matter of "personal taste" either. & and && both exist for a reason, just like | and ||.
When it comes to boolean statements, you are correct on the difference. However, the fundamental difference is that & is a bitwise "and" while && is a logical "and."
There are plenty of situations in which someone might want a bitwise "and," so making its use a blanket error is not a good idea. The most common use case is using it as a mask.
For example, MotionEvent's getAction() method returns an integer with both the pointer index and the action. To get the action, you need to mask the return value like so: getAction() & ACTION_MASK.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I want two compare two SQL where clauses to check if the conditions are similar.
In the below example the SQL queries have same logical conditions in the where clause. What operation shall tell me that both where clause conditions are logically same?
Is there a REGEX for this? Any other approach?
String Q3 = "select t1.ID as ID,t1.FIELD8 as I_RECHARGE_TYPE,t1.FIELD28 as I_RECHARGE_AMOUNT,t1.FIELD1 as I_ACTIVATION_DATE,t1.FIELD2 as I_MSISDN from INSTANT_CDR_0 as t1 where t1.FIELD2 = ? and ((((t1.FIELD8 IS NOT NULL AND t1.FIELD28 > 0) OR DATE_FORMAT(t1.FIELD1,'%Y-%m-%d') > '2016-05-21')) or ((DATE_FORMAT(t1.FIELD1,'%Y-%m-%d') < '2015-12-03' OR ( t1.FIELD28 > 0 AND t1.FIELD28 < 101))))";
String Q4 = "select t1.ID as ID,t1.FIELD1 as I_ACTIVATION_DATE,t1.FIELD8 as I_RECHARGE_TYPE,t1.FIELD28 as I_RECHARGE_AMOUNT,t1.FIELD2 as I_MSISDN from INSTANT_CDR_0 as t1 where t1.FIELD2 = ? and (((DATE_FORMAT(t1.FIELD1,'%Y-%m-%d') > '2016-05-21' OR ( t1.FIELD8 IS NOT NULL AND t1.FIELD28 > 0))) or (((t1.FIELD28 > 0 AND t1.FIELD28 < 101) OR DATE_FORMAT(t1.FIELD1,'%Y-%m-%d') < '2015-12-03')))";
How to compare ((a=2) and (b=3)) with ((b=3) and(a=2)) and figure out they're the same?
A simpler case would be if all the fields you had were booleans. So all the logical expressions would also be boolean expressions.
What you'd then have would be the problem of trying to find out if two boolean expressions are equivalent - that is, for every possible input they provide the same answer.
One approach to doing this might be this: Let A be the first expression and B the second expression and A and B the logical and of the two. For the two expressions to be equivalent A and B applied to all possible inputs must be true. Which means not (A and B) must be false for all inputs. Thus, the last problem becomes a Boolean satisfiability problem. This problem asks whether, for a boolean expression, there exists at least one assignment of inputs which makes it true. If there is, then you can say that the two expressions are not equivalent using our construction, otherwise you say they are equivalent.
The good news is that there's loads of tools for attacking the problem, called SAT-solvers, which are used in a ton of industrial applications (circuit design, for example).
The bad news is that the problem is NP-complete. So it's a really hard one. If the setup of the problem does not lend itself to the usual heuristics employed by SAT-solvers, you're gonna have to wait a while to get your results (perhaps till the heat death of the Universe?).
The worse news is that SAT solvers are focused on boolean problems, while you have SQL data types, which are more general problems. Developing the tooling for solving that is on you, unfortunately.
All this on top of, as others have mentioned, needing to parse the expression.
Depending on how exact you want the result to be, you can do this trick: run the two queries. If they provide the same result, say the expressions are equivalent. If not, say they aren't. What you have here is a situation where you can have false positives, but no false negatives. So, if you say two expressions aren't equivalent, then that's a fact, you can't deny that, because otherwise they'd have provided the same answer. But if you say they are equivalent, there's some chance they're actually not, and you got lucky with your data. If people add more data in the future in the tables, the two won't be equivalent. There's a bit of math here involved, and I won't sketch it in this answer, but, if one makes some assumptions about the input table/tables and one also has enough rows in the tables, the probability of a false positive, that is, of you saying two expressions are equivalent, when in fact they aren't, drops pretty low - exponentially so. So if you have something like 1000 rows to test these things on, you can be pretty sure that a match is good.
You could also do algebraic manipulations on the expressions, trying to bring one to the form of the other. There's a whole set of them one can apply, from boolean expressions (DeMorgan rules, associativity, Karnaugh Maps, etc.), which perhaps might help in finding an exact solution, especially if the where clauses are simple, but that would seem more fragile to me.
Hope this helps. Make sure to order the results of the queries, so you don't discard real matches.
Simple/simplified approach that may not be good enough (initially I didn't see your comment about checking logically). As others pointed out, without relaxations, this problem is NP-Complete...
Use something like JSQLParser to get a structured representation and then traverse the object model and try to compare between the conditions. I would try to make a function that compare two expression and check for equality. This function could be called recursively in case of expressions with deep nesting/parenthesizing.
Try to use regex to split the where clause into conditions and then compare. Here you'd have to be careful with OR/AND and parenthesis... ideally, you'll want to end up with some hierarchical structure that preserve meaning of parenthesizing.
I tend to believe that the first approach would be easier as you won't have to break your neck with breaking/grouping of the conditions based on parenthesis etc.
I'd like to know some cases in Java (or more generally:
in programming) when it is preferred in boolean expressions to use the unconditional AND (&) instead of the conditional version (&&).
I know how they work, but I cannot think about a case when use the single & is worth it.
I have found cases in real life where both sides of the expression were really cheap, so it shaved off a nanosecond or two to avoid the branch and to use the unconditional & instead of &&. (These were extremely high-performance math utilities, though; I would almost never use this in other code, and I wouldn't have done it anyway without exhaustive benchmarking to prove it was better.)
(To give specific examples, x > 0 is going to be super cheap and side-effect-free. Why bother risking a branch misprediction to avoid a test that's going to be so cheap anyway? Sure, since it's a boolean the end result is going to be used in a branch anyway, but if (x >= 0 && x <= 10) involves two branches, and if (x >= 0 & x <= 10) involves only one.)
The only difference is that && and || stop the evaluation as soon as it is known. So for example:
if (a != null && a.get() != null)
works well with &&, but with & you could get a NullPointerException if a is null.
The only case I can think about where you want to use & is if the second operand has a side effect, for example (probably not the best example but you get the point):
public static void main(String[] args) {
int i = 1;
if (i == 0 & ++i != 2) {
}
System.out.println(i); //2
i = 1;
if (i == 0 && ++i != 2) {
}
System.out.println(i); //1
}
However, this looks like smelly code to me (in both cases).
The && allows the jvm to do short circuit evaluation. That is, if the first argument is false, then it doesn't need to bother checking the second argument.
A single & will run both sides regardless.
So, as a contrived example, you might have:
if (account.isAllowed() & logAccountAndCheckFlag(account))
// Do something
In that example, you might always want to log the fact that the owner of the account attempted to do something.
I don't think I have ever used a single & in commercial programming though.
Wikipedia has nicely described the Short Circuit Evaluation
Where do you prefer non short-circuit operators ?
From the same link:
Untested second condition leads to unperformed side effect
Code efficiency
Short-circuiting can lead to errors in branch prediction on modern
processors, and dramatically reduce performance (a notable example is
highly optimized ray with axis aligned box intersection code in ray
tracing)[clarification needed]. Some compilers can detect such cases
and emit faster code, but it is not always possible due to possible
violations of the C standard. Highly optimized code should use other
ways for doing this (like manual usage of assembly code)
If there are side effects that must happen, but that's a little ugly.
The bitwise AND (&) is mostly useful for just that - bitwise math.
Input validation is one possible case. You typically want to report all the errors in a form to the user in a single pass instead of stopping after the first one and forcing them to click submit repeatedly and only get a single error each time:
public boolean validateField(string userInput, string paramName) {
bool valid;
//do validation
if (valid) {
//updates UI to remove error indicator (if present)
reportValid(paramName);
} else {
//updates UI to indicate a problem (color change, error icon, etc)
reportInvalid(paramName);
}
}
public boolean validateAllInput(...) {
boolean valid = true;
valid = valid & validateField(userInput1, paramName1);
valid = valid & validateField(userInput2, paramName2);
valid = valid & validateField(userInput3, paramName3);
valid = valid & validateField(userInput4, paramName4);
valid = valid & validateField(userInput5, paramName5);
return valid;
}
public void onSubmit() {
if (validateAllInput(...)) {
//go to next page of wizard, update database, etc
processUserInput(userInput1, userInput2, ... );
}
}
public void onInput1Changed() {
validateField(input1.Text, paramName1);
}
public void onInput2Changed() {
validateField(input2.Text, paramName2);
}
...
Granted, you could trivially avoid the need for short circuit evaluation in validateAllInput() by refactoring the if (valid) { reportValid() ... logic outside of validateField(); but then you'd need to call the extracted code every time validateField() was called; at a minimum adding 10 extra lines for method calls. As always it's a case of which tradeoff's work best for you.
If the expression are trivial, you may get a micro-optimisation by using & or | in that you are preventing a branch. ie.
if(a && b) { }
if(!(a || b)) { }
is the same as
if (a) if (b) { }
if (!a) if (!b) { }
which has two places a branch can occur.
However using an unconditional & or |, there can be only one branch.
Whetehr this helps or not is highly dependant on what the code is doing.
If you use this, I sugegst commenting it to make it very clear why it has been done.
There isn't any specific use of single & but you can consider the following situation.
if (x > 0 & someMethod(...))
{
// code...
}
Consider that someMethod() is doing some operation which will modify instance variables or do something which will impact behavior later in processing.
So in this case if you use && operator and the first condition fails it will never go in someMethod(). In this case single & operator will suffice.
Because & is a bit-wise operator, you can do up to 32-checks in a single operation concurrently. This can become a significant speed gain for this very specific use cases. If you need to check a large number of conditions, and do it often and the cost of boxing/unboxing the conditions are amortized by the number of checks, or if you store your data on-disk and on-RAM in that format (it is more space efficient to store 32 conditions in a single bitmask), the & operator can give a huge speed benefit over a series of 32 individual &&. For example if you want to select all units that can move, is an infantry, has weapon upgrade, and is controlled by player 3, you can do:
int MASK = CAN_MOVE | INFANTRY | CAN_ATTACK | HAS_WEAPON_UPGRADE | PLAYER_3;
for (Unit u in allunits) {
if (u.mask & MASK == MASK) {
...;
}
}
See my other answers on a related question for more on the topic.
The only benefit I can think of is when you need to invoke a method or execute a code, no matter the first expression is evaluated to true or false:
public boolean update()
{
// do whatever you want here
return true;
}
// ...
if(x == y & update()){ /* ... */}
Although you can do this without &:
if(x == y){/* ... */}
update();
Short-circuiting can lead to errors in branch prediction on modern processors, and dramatically reduce performance (a notable example is highly optimized ray with axis aligned box intersection code in ray tracing)[clarification needed].
I recently received a downvote for using the following in a recent answer:
String word = ...;
if ("s".equals(word) || "y".equals(word)
The downvote was given due to using a "yoda condition". I asked for further explanation but none was provided. I prefer this style to avoid a possible NullPointerException.
Is this a poor coding style? If so, why?
Bill Pugh asked this question at Devoxx 2011. The vast majority of people went for the form "xyz".equals(str). I am with Bill, now preferring str.equals("xyz").
It's fundamental to the Java tradition that we find errors as early as reasonably possible. NPEs are exceptionally common. We want to route these nulls out as soon as possible.
If you're expecting the reference to maybe null, then I don't particularly object to the backwards notation. It's nice to be explicit and easier to understand that there may be a null with a separate null check, but the reverse order should be well understood and sufficiently differentiate the code from the normal case where null is forbidden.
Working in security, some of the bugs null-tolerance accommodates are vulnerabilities.
Yoda conditions (i.e. putting a constant before a variable in a comparison) can be considered bad practice as it makes the line of code less comprehensible. In this specific case however I would state that using a Yoda condition makes the code more comprehensible as you don't have to put a extra null check in front of it.
Visit the following link to understand what is meant by Yoda Conditions|Notation
Its not a "poor coding style" its diferent way of coding.
Yoda can be usefull to track typos in some languages, i believe the -1 was not deserved to be honest but that is my personal opinion.
But Yoda can be bad as explained in this lengthy but very interesting article.
End of the day, there are supporters in favor and against this kinda of notation.
Well, it depends. If in your program "word" should never be null, word.equals("s") may actually be better. If for some obscure reason "word" will become null, you will get NullPointerException.
Think about it. If you get exception, you know something went wrong, and you can faster find mistake and fix it. If program will continue to work silently, and produce wrong results, it will be much harder to detect the problem. Actually, you may not notice there is the problem at all.
It all depends.
There are several reasons not to do it like that, however in the end it depends on you (or the team working on your product) if you think this is bad coding style. Arguments against it are:
Strings are rarely null (and you shouldn't make APIs where they are because people don't expect it)
It feels weird to put the value you are comparing to first
Code style uniformity is important, because this way is the exception, you should only do it, if everyone in your team does it.
As said I don't think these arguments are very strong, nor is the reason to do it like you. So it is mostly important to just agree on one way as your coding style and stick to that.
TL;DR; This definitely is poor coding style NOT :D
well, the yoda conditions are useful in languages where non-boolean can evaluate to a boolean value, e.g.
int test = 0;
if ( test ){ /* do something */
but this is not allowed in Java so you don't run into problems such as forgetting '=', e.g.
if ( test = 2 ){ /* do something */
instead of test == 2
the compiler will not let you do this. So the yoda condition may seem unnatural to someone who has not had to care about this (because he/she didn't use any other language but Java).
This definitely is NOT poor coding style it is just not very common to see Java code using it
yoda condition is where oup put the literal in front of the variable.
word.equals("s") is read as "word equals s"
"s".equals(word) a human reads as "s equals word"
Our brains read the first example much better and the code is clearer.
the only reason imho to use yoda conditions is to prevent assignment
as in "if (42 = i)" instead of "if(42 == i)"
You can write
if (word != null && (word.equals("s") || word.equals("y")))
instead of
if ("s".equals(word) || "y".equals(word))
In this case, first one will never cause any NullpointerException, but in my point of view in this case the 2nd one is better, though it is in Yoda Condition
There is a special case pf Yoda conditional I've not seen defended, or attacked, in any of the answers, so I'll add it for reference. This is the style of:
if(0 < x && x <= max) {
A Yoda conditional because the constant (0) is before the variable (x). The argument against Yoda conditionals is that is hinders readability. Contrast that example with the functionally equivalent
if(x <= max && x > 0) {
Do you really think that, non-Yoda variant, is more readable? I don't.
For readability when using ordering relational operators (<, <=, >, >=), I prefer the style of these heuristics:
Use consistent ordering relations: > is consistent with >=, but not with < or <=; < is consistent with <=.
Prefer < and <= to > and >=, as the default is ascending order.
Place conditions that impose a lower bound on the variable before conditions that impose an upper bound, if using < and <=. Do the opposite if using > and >=.
This very often produces a Yoda conditional for the lower bound.
One might argue that you should (unit-)test your code enough to be confident that nulls don't go where they're not supposed to. This should obviate the need for yoda conditions.
I'm trying to make my code more readable, so I decided to use some short IF statements.
Here's my code which doesn't work ("not a statement"):
jXPanel6.isVisible() ? jXPanel6.setVisible(true) : jXPanel6.setVisible(false);
What's wrong with this? Needs brackets? Where?
The "ternary expression" x ? y : z can only be used for conditional assignment. That is, you could do something like:
String mood = inProfit() ? "happy" : "sad";
because the ternary expression is returning something (of type String in this example).
It's not really meant to be used as a short, in-line if-else. In particular, you can't use it if the individual parts don't return a value, or return values of incompatible types. (So while you could do this if both method happened to return the same value, you shouldn't invoke it for the side-effect purposes only).
So the proper way to do this would just be with an if-else block:
if (jXPanel6.isVisible()) {
jXPanel6.setVisible(true);
}
else {
jXPanel6.setVisible(false);
}
which of course can be shortened to
jXPanel6.setVisible(jXPanel6.isVisible());
Both of those latter expressions are, for me, more readable in that they more clearly communicate what it is you're trying to do. (And by the way, did you get your conditions the wrong way round? It looks like this is a no-op anyway, rather than a toggle).
Don't mix up low character count with readability. The key point is what is most easily understood; and mildly misusing language features is a definite way to confuse readers, or at least make them do a mental double-take.
jXPanel6.setVisible(jXPanel6.isVisible());
or in your form:
jXPanel6.setVisible(jXPanel6.isVisible()?true:false);
The ternary operator can only be the right side of an assignment and not a statement of its own.
http://www.devdaily.com/java/edu/pj/pj010018/
As others have indicated, something of the form
x ? y : z
is an expression, not a (complete) statement. It is an rvalue which needs to get used someplace - like on the right side of an assignment, or a parameter to a function etc.
Perhaps you could look at this: http://download.oracle.com/javase/tutorial/java/nutsandbolts/expressions.html
I'm a little late to the party but for future readers.
From what i can tell, you're just wanting to toggle the visibility state right? Why not just use the ! operator?
jxPanel6.setVisible(!jxPanel6.isVisible);
It's not an if statement but I prefer this method for code related to your example.
You can do it as simple as this, I did it in react hooks :
(myNumber == 12) ? "true" : "false"
it was equal to this long if function below :
if (myNumber == 12) {
"true"
} else {
"false"
}
Hope it helps ^_^