Get all the conditions which resulted in rule execution - java

I want to get all the individual conditions which resulted in the execution of a rule.
For example, if I have the following rule:
package app1;
rule 'rule1'
when
MyObjectType1( booleanPredicate1() )
or
(
MyObjectType2( booleanPredicate2() )
and
MyObjectType3( booleanPredicate3() )
)
or
MyObjectType4( booleanPredicate4() )
then
System.out.println("In rule - " + drools.getRule().getName());
end
and booleanPredicate1(), booleanPredicate2() and booleanPredicate4() are true, then I want to get the following output:
booleanPredicate1() resulted in rule execution.
booleanPredicate4() resulted in rule execution.
What I've tried so far is inside the implementation of all such predicate methods, I've added a logging statement which gets executed only when that method is going to return true:
boolean booleanPredicate1()
{
boolean ret = false;
...
...
if (<business-logic-defined-predicate>)
{
ret = true;
}
if(ret)
{
addToLog("booleanPredicate1 became true.");
}
return ret;
}
but with this solution, I'll also get the output booleanPredicate2() resulted in rule execution. which is wrong.
Is there any way with which I can get the correct logging results?

Consult my paper on rule design patterns it has a section answering your question.
To summarize it here: you need rules for the individual truth values to register what is true for some fact or some combination of facts. The rule as you have it now will then combine the boolean values from the registry, and registry contains the answer to your problem.

Related

How to check whether Junit is running with JunitRunner or PowermockRunner

During writing junits to the classes, I got some requirement like executing tests in with different runners like once with JUnitRunner and then with PowermockRunner, so based on that I want to decide whether to skip test or continue. Please could you let me know is there any way to check like this?
Thanks in advance.
There are several options, but none of them is pretty.
Your best bet would be if either of these runners supported a system property that you can query, but I doubt that.
Failing that, you can either do a class lookup or inspect the stack.
Class Lookup
boolean isPowerMock = false;
try{
Class.forName("fully.qualified.name.of.PowerMockRunner");
isPowerMock = true;
}catch(ClassNotFoundException e){}
Note that this technique may return a false positive if PowerMock is on the class path, but the runner isn't used.
Inspect stack
boolean isPowerMockRunner = false;
for (StackTraceElement stackTraceElement : Thread.currentThread().getStackTrace()) {
if(stackTraceElement.getClassName().contains("PowerMockRunner")) {
isPowerMockRunner = true;
break;
}
}
Or, Java 8-style:
boolean isPowerMock = Arrays.stream(
Thread.currentThread()
.getStackTrace()
)
.anyMatch(
elem -> elem.getClassName()
.contains("PowerMockRunner")
);

Should I minimize the number of "if" statements or "for" loops?

I have a list of Objects that need to have multiple, conditionally applied, operations applied to each element. Is it more efficient to take a "if-for" approach or a "for-if" approach. To put it another way, should I minimize the number of if statements or the number of for loops? Is there a standard for this?
What would be a good reliable way to determine this?
"If-For" to Approach minimize if statements
public void ifForMethod() {
if (conditionA) {
for (Object o : listOfObjects) {
doA(o);
}
}
if (conditionB) {
for (Object o : listOfObjects) {
doB(o);
}
}
}
"For-If" Approach to minimize for loops
public void forIfMethod() {
for (Object o : listOfObjects) {
if (conditionA) {
doA(o);
}
if (conditionB) {
doB(o);
}
}
}
Assumptions
The conditions are simple booleans and will not change while iterating.
One or more conditions will be true. (there are more than 2 conditions)
Each condition is independent of the other conditions.
The inner methods do not conflict or interact with each other at all. The order in which they are executed is irrelevant.
There is no reason to make 2 passes over the list.
Assumptions: predicates are simple booleans, if they have to be evaluated then obviously the cost can change things.
If ((condtionA || conditionB) == true) then both If-for and For-If are both 1 pass. If both predicates can be true then obviously you only want to make one pass.
It doesn't matter what doA and doB since we're assuming they're they same in both If-for and For-If.
If the predicates can change over the course of evaluation then that must be considered.
You're asking a general question so answers are general and vague without more details.
Ok now that you've provided additional info (the list is only 5 elements long, this is part of a build process, the predicates are static booleans) we can see that the bottleneck here is the doA/B functions. Therefore you should only go through the loop once. The static boolean checks are negligible.
Using what you called the "If-For" way rather than "For-If" is (perhaps a slightly more general version of) an optimization called loop unswitching. Whether it's actually a good idea depends on several factors, such as (but not limited to)
whether that transformation is even allowed (ie conditions have no side effects and doA and doB may be reordered)
what you're optimizing for (eg speed, readability, or w/e) though in this case that doesn't really make a difference
whether the array fits in cache (iterating over it twice could double the number of cache misses)
what the (JIT) compiler makes of it exactly, for example whether the conditions actually compile to branches or not or maybe the compiler does the loop unswitching for you
the processor microarchitecture (some µarchs dislike branches inside loops more than others, even if those branches are highly predictable)
First, let's take a look at the complexity of the methods that you've shown so far:
The ifForMethod performs k checks, m of which return true. For each of these m, there is an iteration over n objects. The complexity, then, is k+nm.
The forIfMethod iterates over n objects and performs k comparisons on each iteration. The complexity, then, is k+n(k-1)=nk.
In both cases, all k conditions have to be evaluated at least once, so the difference here really is in the nm and n(k-1) addends. Asymptotically, m is a just a fraction of k (you said m is approximately .75k), so these are both O(nk), but k+nm < k+n(k-1), so the ifForMethod might be a faster than forIfMethod. The difference in actual run time is going to depend on factors such as the actual time that it takes to iterate over the array, as well as the magnitude of k. You're going to start getting into issues such as memory locality (both for your objects as well as your code).
Here's an approach that you might find interesting, though. Ideally, you'd only want to iterate through the list of objects once, and you wouldn't want to have to check the boolean conditions multiple times. You could abstract away the actions that you're performing in such a way that you could combine them into a single action (and you'd only incorporate those actions that correspond to the conditions that are true), and then perform that compound action on each element in the list. Here's some code that does this.
The idea is that there are Actions, and that you can construct an Action that performs doA and an Action that performs doB. Based on the conditions, you can create a compound action that includes the doA action if the doA condition is true, and the doB action if the doB condition is true. Then you iterate through the objects, and call perform the compound action on each object. Asymptotically, this is a k+nm method, so in theory it performs nicely, but again, the actual performance here will depend on some of those tricky constants, and memory locality issues.
import java.util.ArrayList;
import java.util.List;
public class CompoundActionExample {
/**
* An action is used to do something to an argument.
*/
interface Action {
void act( Object argument );
}
/**
* A compound action is an action that acts on an argument
* by passing the argument to some other actions.
*/
static class CompoundAction implements Action {
/**
* The list of actions that the compound action will perform. Additional
* actions can be added using {#link #add(Action)}, and this list is only
* accessed through the {#link #act(Object)} method.
*/
private final List<CompoundActionExample.Action> actions;
/**
* Create a compound action with the specified list of actions.
*/
CompoundAction( final List<CompoundActionExample.Action> actions ) {
this.actions = actions;
}
/**
* Create a compound action with a fresh list of actions.
*/
CompoundAction() {
this( new ArrayList<CompoundActionExample.Action>() );
}
/**
* Add an action to the compound action.
*/
public void add( CompoundActionExample.Action action ) {
actions.add( action );
}
/**
* Act on an argument by passing the argument to each of the
* compound action's actions.
*/
public void act( final Object argument) {
for ( CompoundActionExample.Action action : actions ) {
action.act( argument );
}
}
}
public static void main(String[] args) {
// Some conditions and a list of objects
final boolean conditionA = true;
final boolean conditionB = false;
final Object[] listOfObjects = { "object1", "object2", "object3" };
// A compound action that encapsulates all the things you want to do
final CompoundAction compoundAction = new CompoundAction();
// If conditionA is true, add an action to the compound action that
// will perform doA. conditionA is evaluated exactly once.
if ( conditionA ) {
compoundAction.add( new Action() {
public void act( final Object argument) {
System.out.println( "doA("+argument+")" ); // doA( argument );
}
});
}
// If conditionB is true, add an action to the compound action that
// will perform doB. conditionB is evaluted exactly once.
if ( conditionB ) {
compoundAction.add( new Action() {
public void act(Object argument) {
System.out.println( "doB("+argument+")" ); // doB( argument );
}
});
}
// For each object, apply the compound action
for ( final Object o : listOfObjects ) {
compoundAction.act( o );
}
}
}
It Depends on the nature of the business problem your code is trying to solve. If both conditionA AND conditionB are simple Boolean variables but not expressions, then the For-If is going to be better as you are cycling through the list of objects only once.
We are basically comparing which performs better : Enumerating from a list of objects multiple times or evaluating a boolean expression multiple times. If your conditionA/conditionB are very complex Boolean expressions, then your If-For would be a better approach.
lets consider that we are doing same number of operation in both the for loop and inside if .With this standard i will go with the first approach which using if statement before executing for loop just to avoid the number of iteration in for loop.
Also as you are using advance for loop which takes more time to execute the same operation compare to normal for loop.
please correct me if i am wrong.
It depends! The ifForMethod() solution is best, if there are real cases where neither conditionA nor conditionB is true. If there are cases where conditionA and conditionB are true, solution forIfMethod() is the best but the conditions should be precalculated before entering the loop.
But you can modify forIfMethod() to make it suitable for all cases:
public void forIfMethod() {
boolean a = conditionA;
boolean b = conditionB;
if (a || b) {
for (Object o : listOfObjects) {
if (a) {
doA(o);
}
if (b) {
doB(o);
}
}
}
}
the first one (if-for) sounds good for me.. because for first case there will be a single checking for whole for loop. But in the second cases there will be checking for every loop.
The second one is more efficent in terms of how many comparisons you make.
Check condition a, 1 calculation.
If true, Object.size calculatons.
Check condition b, 1 calculation.
If true, Object.size calculations.
Min, 2, Max Object.size * 2
For Method 2, you will always have Object.size * 2 calculations performed.
Consider your "worst case" if both checks are false. Way 1 will only do 2 calculations. Way 2 will perform Object.size * 2. It has nothing to do with your function as in both cases it will always take the same amount of time in both cases.
Even in your "best case" if both checks are true, you are still performing that check N-1 times more for A, and N-1 times more for B.
Best way I think to do it with the fewest calculations.
public void ifForMethod() {
if (conditionA) {
if(conditionB){
for (Object o : listOfObjects) {
doA(o);
doB(o);
}
else{
for (Object o : listOfObjects) {
doA(o);
}
}
}
else if (conditionB) {
for (Object o : listOfObjects) {
doB(o);
}
}
}
You perform 2 check operations and then only loop through the list once, at max.
I think it depends on more things, like: If you find the conditionA, will the loop break? The conditionA and conditionB can coexist? Could I use if-else with them?
Just looking for what you've presented, I think the second aproach is better. You're only looping once and checking twice in the same loop. In my opinion it's also more readable.
Several things:
Is this a premature optimization? Does it really matter if one way is faster than the other, depending on the data it might not be a human noticeable difference.
I would question the design of the software. Why is the same Object have 2 possible conditions? I would recommend breaking the design into multiple objects. Perhaps using subclasses to do the different logic or use the Strategy Pattern. I can't be more specific without a better idea of what you are doing.

Break in a method called from a loop

I'm refactoring a very large method with a lot of repetition in it.
In the method there are many while loops which include:
if ( count > maxResults){
// Send error response
sendResponse(XMLHelper.buildErrorXMLString("Too many results found, Please refine your search"), out, session);
break;
I want to extract this as a method, because it happens 3 times in this one method currently, but when I do so I get an error on the break as it is no longer within a loop. The problem is that it is still necessary to break out of the while loops, but only when the maximum number of results are reached.
Any suggestions?
Suppose the method is :
public boolean test(int count, int maXResult) {
if ( count > maxResults) {
// Send error response
sendResponse(XMLHelper.buildErrorXMLString("Too many results found, Please refine your search"), out, session);
return true;
}
return false;
}
Call method from loop as :
while(testCondition) {
if (test(count, maxResults)) {
break;
}
}
This is impossible to do directly.
Most often you want to break because you have found the solution and no longer have to search. So indicate in the called function that there is/was success, for instance by returning a result or a boolean to indicate success. And if the function returns success, then break.
If it is now within a method instead of the while loop have it return a value and then break based on that.
i.e.
public bool refactoredMethod(parameters)
{
if ( count > maxResults){
// Send error response
sendResponse(XMLHelper.buildErrorXMLString("Too many results found, Please refine your search"), out, session);
return true;
}
return false;
}
Try to break the loop in the method using return;
As Thriler says you cant do it directly. You could extract part of it to the method and do something like:
if(isTooManyResults(count)) { break; }
Obviously your isTooManyResults method would need to return true if there are too many results and false otherwise

Using Return Stylishly

Let's say I had a lot of code between an if statement. Is it more proper to do a quick if-else check before it, and if it fails, return.
OR create the if statement with a lot of code in-between but not use return?
OR is it just a matter of preference?
so my 2 options are:
if(!something){
return
}
else
//lots of code here
if(something){
//lots of code here
}
From a performance perspective, you should always return from a function as quickly as you can, avoid doing unnecessary computations, "short-circuit" if you will. So checking for error cases and returning quickly would be the better policy.
Edit to add: In the same vein, you should always check the cases that are most likely to be violated first, this is sound advice when structuring your conditionals as well (|| and && checks)
I think this looks much nicer:
func() {
if(someCondition) {
return;
}
if(otherCondition) {
return;
}
//lots of code
}
than this:
func() {
if(someCondition) {
return;
} else if(otherCondition) {
return;
} else {
//lots of code
}
}
or this:
func() {
if(!someCondition) {
if(!otherCondition) {
//lots of code
}
}
}
It looks even uglier with more conditions, so I generally use the first method.
I prefer "shortcut". It has nothing to do with performance, as modern computer can handle if-else very fast, so we should focus on code readability.
However, if there's so many if-else in code, you may re-think your design. Refactory can be a better choice.
Readability and performance are not necessary conflicting constraints but when they are I tend to give readability the front seat.
To enhance readability I tend to follow the following rules.
Rule 1. Keep return as the last line of code, whatever comes in the middle. In other words don't sprinkle return statements whenever you want just because you're not too sure your if-else structure will cascade down just before the final return.
Except may be for the simplest methods I privilege a structure like
MyType func() {
MyType result ;
if ( condition ) {
result = result_1 ;
} else {
result = result_2 ;
}
return result ;
}
over an allegedly simpler
MyType func() {
if ( condition ) {
return result_1 ;
} else {
return result_2 ;
}
}
In my opinion the performance cost, if any, is negligible. However, when scaled up, I find the first coding pattern much more readable.
Rule 2. Refrain from starting a logic by "evacuating" error conditions, just in order to get them out of the way and free your mind. If your logic is well thought these checks will find their place in the logic (also have a look at guava for many well though techniques of encapsulating routine checks in helpers).
Many freshmen in my team start coding things like this
MyType func (ArgType arg1,...) {
if ( arg1 == null ) {
throw new Exception ( "hey dummy, we don't take null arg1) ;
// or return null ;
}
if ( arg2 == null ) {
// you got the picture...
}
// wow at last !!! all checks done
// Combine args and return result...
}
Which I have to say, is already a progress on just taking all conditions for granted
I tend to prefer
MyType func (ArgType arg1,...) {
MyType result ;
if ( try_to_compact_all_checks_here ) {
// Combine args and return result...
} else {
// throw, log, nullify result etc
}
return result ;
}
If the condition "try_to_compact_all_checks_here" does not fit in one line, I even sometimes prefer to get out of my way and I encapsulate all the checks in a private function. Even if it's called only once.
Rule 3. Keep the number of lines in an if/else statement to a reasonable amount (basically should fit on one screen in your IDE). To do so it is sometimes possible to extract some logic and stick it into a private function. No problem at all. All modern IDE do that for you in 2 clicks.
So basically the previous template becomes.
MyType func (ArgType arg1,...) {
MyType result ;
if ( checks_here ) {
// 1 to 20 lines max,
encapsulate lengthy logic in full fledged private methods.
} else {
// throw, log, nullify result etc
}
return result ;
}
Rule 4. Inner IFs should always have an ELSE, and that ELSE should be different from the outer ELSE.
Explanation: If I end up with
MyType func (ArgType arg1,...) {
MyType result ;
if ( check_1 ) {
if (check_2) {
Do the real work
} else {
treat error condition
}
} else {
same error condition as above
}
return result ;
}
Then it's probably because my check analysis is not complete. It happens quite often.
I try to reach
MyType func (ArgType arg1,...) {
MyType result ;
if ( check_1 && check_2) {
Do the real work
} else {
same error condition as above
}
return result ;
}
That's all.
I found that, by observing this kind of conventions, I can process large Java projects with ofter complex business logics (like in ESBs, Web Services etc), at very little performance cost if any.

Purpose of "return" statement in Scala?

Is there any real reason of providing the return statement in Scala? (aside from being more "Java-friendly")
Ignoring nested functions, it is always possible to replace Scala calculations with returns with equivalent calculations without returns. This result goes back to the early days of "structured programming", and is called the structured program theorem, cleverly enough.
With nested functions, the situation changes. Scala allows you to place a "return" buried deep inside series of nested functions. When the return is executed, control jumps out of all of the nested functions, into the the innermost containing method, from which it returns (assuming the method is actually still executing, otherwise an exception is thrown). This sort of stack-unwinding could be done with exceptions, but can't be done via a mechanical restructuring of the computation (as is possible without nested functions).
The most common reason you actually would want to return from inside a nested function is to break out of an imperative for-comprehension or resource control block. (The body of an imperative for-comprehension gets translated to a nested function, even though it looks just like a statement.)
for(i<- 1 to bezillion; j <- i to bezillion+6){
if(expensiveCalculation(i, j)){
return otherExpensiveCalculation(i, j)
}
withExpensiveResource(urlForExpensiveResource){ resource =>
// do a bunch of stuff
if(done) return
//do a bunch of other stuff
if(reallyDoneThisTime) return
//final batch of stuff
}
It is provided in order to accommodate those circumstances in which it is difficult or cumbersome to arrange all control flow paths to converge at the lexical end of the method.
While it is certainly true, as Dave Griffith says, that you can eliminate any use of return, it can often be more obfuscatory to do so than to simply cut execution short with an overt return.
Be aware, too, that return returns from methods, not function (literals) that may be defined within a method.
Here is an example
This method has lots of if-else statements to control flow, because there is no return (that is what I came with, you can use your imagination to extend it). I took this from a real life example and modified it to be a dummy code (in fact it is longer than this):
Without Return:
def process(request: Request[RawBuffer]): Result = {
if (condition1) {
error()
} else {
val condition2 = doSomethingElse()
if (!condition2) {
error()
} else {
val reply = doAnotherThing()
if (reply == null) {
Logger.warn("Receipt is null. Send bad request")
BadRequest("Coudln't receive receipt")
} else {
reply.hede = initializeHede()
if (reply.hede.isGood) {
success()
} else {
error()
}
}
}
}
}
With Return:
def process(request: Request[RawBuffer]): Result = {
if (condition1) {
return error()
}
val condition2 = doSomethingElse()
if (!condition2) {
return error()
}
val reply = doAnotherThing()
if (reply == null) {
Logger.warn("Receipt is null. Send bad request")
return BadRequest("Coudln't receive receipt")
}
reply.hede = initializeHede()
if (reply.hede.isGood)
return success()
return error()
}
To my eyes, the second one is more readable and even manageable than the first one. The depth of indentation (with well formatted code) goes deep and deep if you don't use a return statement. And I don't like it :)
I view return as a useful when writing imperative style code, which generally means I/O code. If you're doing pure functional code, you don't need (and should not use) return. But with functional code you may need laziness to get performance equivalent to imperative code that can "escape early" using return.

Categories