Expression resolver and condition builder - java

I have multiple expression like
c1|<|5&&c2|>=|750&&c3|=|1
c1|<|5&&(c2|>=|750||c3|=|1)
c1|<|5&&(c2|>=|750||c3|=|1)&&c4|=|1
c1|<|5&&c2|>=|750||c3|=|1&&c4|=|1
(c1|<|5||c2|>=|750||c3|=|1)&&c4|=|1
Now what I want to do here is basically I want to parse the expression and using interfaces for && and || I want to build the condition builder which basically takes the condition and then evaluate the final expression. Is there is any in Java without using any external library and using Java oops concepts where
c1|<|5&&c2|>=|750&&c3|=|1 -> (c1|<|5) && (c2|>=|750) && (c3|=|1)
c1|<|5&&(c2|>=|750||c3|=|1) -> (c1|<|5) && ((c2|>=|750) || (c3|=|1))
c1|<|5&&(c2|>=|750||c3|=|1)&&c4|=|1 -> (c1|<|5) && ((c2|>=|750) || (c3|=|1)) || (c4|=|1)
Any help would be really helpful.

Related

Is there a limit to how long an if statement can be in Java?

I was working on a game called the L game. In the function to check for a win, I had an if statement like this:
if (buttons[i][0].getText().equals(colour) || buttons[i][0].getText().equals("0") && buttons[i][1].getText().equals(colour) || buttons[i][1].getText().equals("0") && buttons[i][2].getText().equals(colour) || buttons[i][2].getText().equals("0") && buttons[i+1][2].getText().equals(colour) || buttons[i+1][2].getText().equals("0") && !(buttons[i][0].getText().equals(colour) && buttons[i][1].getText().equals(colour) && buttons[i][2].getText().equals(colour) && buttons[i+1][2].getText().equals(colour))) {
return false;
}
And this code didn't work. Not that I was getting an error, just it was not doing what it was supposed to do when a player won. However changed it to a few if statements in each other like this:
if (buttons[i][0].getText().equals(colour) || buttons[i][0].getText().equals("0")) {
if (buttons[i][1].getText().equals(colour) || buttons[i][1].getText().equals("0")) {
if (buttons[i][2].getText().equals(colour) || buttons[i][2].getText().equals("0")) {
if (buttons[i+1][2].getText().equals(colour) || buttons[i+1][2].getText().equals("0")) {
if (!(buttons[i][0].getText().equals(colour) && buttons[i][1].getText().equals(colour) && buttons[i][2].getText().equals(colour) && buttons[i+1][2].getText().equals(
return false;
}
}
}
}
}
And this does work.
Your two code snippets behave differently not because you have exceeded some "maximum characters in an if statement" limit, but because && has a higher precedence than ||.
When you say:
A || B && C || D
You meant
(A || B) && (C || D)
But without any parentheses, Java thought you meant:
A || (B && C) || D
This is because && has a higher precedence than ||. It's kind of like how you do multiplication first, than addition.
That aside, there is theoretically no limit on how long an if condition can be. It is not specified in the Java Language Specification. As long as you have enough RAM for the compiler, disk space to store the source file, and time for the compilation process, your code should compile eventually, if we assume the compiler implements the spec perfectly.
This doesn't mean that you should be writing super long if statements, though. Code is not only read by computers. Arguably, it is more often read by people than computers. So please keep that in mind when writing code.
A first step to refactoring your code would be to write a method like this:
private bool isButton0(int x, int y) {
return buttons[x][y].getText().equals("0");
}
so that you don't have to repeatedly say buttons[i][1].getText().equals("0").

Minifying Or/And expressions in Java?

I've always been curious if it's possible to simplify an Or expression Java. Example:
int mapVal = occurrenceMap.get(node.nextNode.nodeVal);
if (mapVal != null || mapVal != 5 )
versus...
if (occurrenceMap.get(node.nextNode.nodeVal) != ( null || 1) )
IMO, the second is more readable, but wondering if the language supports something like this.
Use getOrDefault
occurrenceMap.getOrDefault(node.nextNode.nodeVal, 5) != 5
if (occurrenceMap.get(node.nextNode.nodeVal) != ( null || 1) )
the second is more readable, but wondering if the language supports
something like this.
No Java not support that.
For a good solution I would like to use :
Integer i = occurrenceMap.get(node.nextNode.nodeVal);
if (i != null || i != 1)
Note : as Tim Biegeleisen mention in comment primitive int or type in general can't be null in Java.
First, int cannot be null. You don't need to check against null if you have an int. It just cannot happen.
Here is a method that checks whether a value is equal to any of a list of values:
public static <T> boolean anyEquals(T value, T... values) {
for (T val: values) {
if (val == value) { // or val.equals(value)
return true;
}
}
return false;
// implementation with streams
// return Arrays.stream(values).anyMatch(x -> x == value); // or x.equals(value)
}
Usage (supposing you are using Integers instead of int):
Integer i = ...;
boolean b = anyEquals(i, 5, 10, 15);
If you're into simplifying boolean expressions you should learn about some axioms and laws:
!!a = a
(!a || a) = true
(!a && a) = false
(true && a) = a
(false && a) = false
(true || a) = true
(false || a) = a
(!a || !b) = !(a && b)
(!a && !b) = !(a || b)
(a != b) = !(a == b)
(a <= b) = (b > a)
(a >= b) = (b < a)
The second one you've mentioned can't possibly be used in
Java because (a || b) already has a meaning so a == (c || d) already has a fixed meaning and changing this would probably break a lot of code. There might be languages that support such notations but they'll use a different operator instead of the binary boolean operator because otherwise it'd be impossible to distinguish what the programmer actually wants.
You could absolutely add such a feature to Java but you'd have to create a new operator to do this. But as of now: Java doesn't have this, and most languages don't.
Some languages allow you to do things like "a < b < c" which not all languages support (you'll have to write "a < b AND b < c").
You technically can create helper functions for this such as
"if isOneOf(mapVal, a, b)" but probably this is not going to be used widespread (most importantly because it'd require some runtime trickery to do this).

Multiple conditions in one if statement in JAVA [duplicate]

Lets say I have this:
if(bool1 && bool2 && bool3) {
...
}
Now. Is Java smart enough to skip checking bool2 and bool3 if bool1 was evaluated to false? Does java even check them from left to right?
I'm asking this because i was "sorting" the conditions inside my if statements by the time it takes to do them (starting with the cheapest ones on the left). Now I'm not sure if this gives me any performance benefits because i don't know how Java handles this.
Yes, Java (similar to other mainstream languages) uses lazy evaluation short-circuiting which means it evaluates as little as possible.
This means that the following code is completely safe:
if(p != null && p.getAge() > 10)
Also, a || b never evaluates b if a evaluates to true.
Is Java smart enough to skip checking bool2 and bool2 if bool1 was evaluated to false?
Its not a matter of being smart, its a requirement specified in the language. Otherwise you couldn't write expressions like.
if(s != null && s.length() > 0)
or
if(s == null || s.length() == 0)
BTW if you use & and | it will always evaluate both sides of the expression.
Please look up the difference between & and && in Java (the same applies to | and ||).
& and | are just logical operators, while && and || are conditional logical operators, which in your example means that
if(bool1 && bool2 && bool3) {
will skip bool2 and bool3 if bool1 is false, and
if(bool1 & bool2 & bool3) {
will evaluate all conditions regardless of their values.
For example, given:
boolean foo() {
System.out.println("foo");
return true;
}
if(foo() | foo()) will print foo twice, and if(foo() || foo()) - just once.
Yes,that is called short-circuiting.
Please take a look at this wikipedia page on short-circuiting

Dynamic Conditional Statement

I want to create dynamic conditional statement in java
following are my expression in file,There are hundreds of expression and they keep on changing
0001|((condition1 == 100) && ((condition2 == 1) || (condition2 == 2) || (condition2 == 3)) && (condition3 > 74))
0002|((condition1 == 100) && ((condition2 == 1) || (condition2 == 2) || (condition2 == 3)) && (condition3 > 59) && ((condition4 == 3) || (condition5 > 30)))
These expression are hardcoded in my class.
if(condition1==100 && ((condition2 == 1) || (condition2 == 2) || (condition2 == 3))){
if(condition3>74){
return "0001"
}
if(condition3>59 && ((condition4 == 3) || (condition5 > 30))){
return "0002"
}
}
i want to create dynamic conditional statement like
first i have check for all expressions which have condition1==100
then for ((condition2 == 1) || (condition2 == 2) || (condition2 == 3))
then return value according to final condition
it is something like first DFS and then BFS
can some body can give me idea how to check first Depth and then Bredth First in java
Your case is : You want define very many conditions and change it continous. You need to have a solution for change dynamically expression and define new condition.
There are two solution for dynamic situation such as your case:
Using Rule Engine. This has very benefit, you can see more information from http://java.sun.com/developer/technicalArticles/J2SE/JavaRule.html
and you can see its open source implementation from here .
Using Dynamic Language or Script Language and Script api.
in second solution you have several choise. I writing some in following:
Groovy: A complete and wonderful script language. see http://groovy.codehaus.org/
Spring Expression Language: Spring solution for calling simple expression. see http://static.springsource.org/spring/docs/3.0.5.RELEASE/reference/expressions.html
BeanShell: A simple but wonderful script language.
There are more dynamic language such as JRuby that you can see it by simple searching in web.
You can read more information for Script api in java from here.
Edited:
For sample, you can use BeanShell Script Language as follwoing:
First create a file with name test.bsh containg blow contents:
if(variable_1 == 100 )
{
System.out.println("Sample condition checked and is true.");
}
else
{
System.out.println("Sample condition checked and is false.");
}
Second set variable_1 from java:
import bsh.*;
Interpreter bsh = new Interpreter ();
bsh.set ("variable_1", 100);
and in final call script as following:
bsh.source (script);
and result will be as following:
Sample condition checked and is true.
by this approach you can change test.bsh content without recompile or restart.

Java coding standards and multiple IF's

I have the following lines of code:
if(
checker.this()==false ||
checker.that()==false ||
checker.what()==true||
checker.cool()==false ||
checker.damm()==true
(...)
)
{
option = Option.FALSE;
}
With about 20 checks that must be performed. I've found this to be the most 'visual-tolerable' form of writing this if with multiple OR sequence but I'm not yet satisfied. Is there a coding standard for this?
Thanks.
The closest thing to a coding standard around this is Steve McConnel, whose authoritative book "Code Complete" recommends that complex conditions are factored into their own method, even if they are only used once. This allows for the name of the method to descibe what is happening.
if (checkValid(checker)) {...}
private boolean checkValid(Checker checker) {...}
checkValid is not a good name, of course, and should be replaced with something more descriptive. In this particular case you may want to make the check method part of "checker" object.
You should also avoid "something==true" and "something==false", and use "something" and "!something". This process is helped if you give the boolean methods appropriate names, like "isOpen()", "isEmpty()", rather than "open()" and "empty()". "checker.isOpen() && !checker.isEmpty()" is perfectly clear to read.
foo==false should better be written with !foo
Possibly, you can move this big if in a separate method: if (checker.complexConditionMet()) or if (complexConditionMet(checker)). It will improve readability.
checker.this()==false can be replaced by !checker.this()
I have never heard of a coding standard for anything like this. Personally, I would group several ifs into a method taking readability into consideration. For instance if you have something like:
if (this || that || what || where || why || cool || wow){ ... }
You could replace it with:
if (pronouns() || questions() || exclamations()){ ... }
I'd try to find common meaning between any of the various checks, and create functions from them.
When bundled together to describe a certain discrete, meaningful state of affairs or requirement, this can make the code less magical, easier to read, easier to test.
i.e. something like this, which is a bit "magical"
if (a == "world" || b == "dolly" || c == 42 || murder()) {
}
can be rendered more readable by changing it to something more like this:
if ( canSayHello() || canMeanLife()) {
}
...
boolean canSayHello() {
return a == "world" || b == "dolly"
}
boolean canMeanLife() {
return c == 42 || murder();
}

Categories

Resources