问题
Say I have code like this:
boolean ret = a() && b() && c() && d() && e();
Usually e() is only called if all other calls a()-d() return true. Is there maybe some compiler or JVM option to disable short circuit evaluation, so e() would be called always, regardless of other functions' results?
Basically I am doing UAT of huge system and need to test e(), however setting up environment and scenario that assures all a(), b() etc. return true is extremely painful...
EDIT: ok, I guess using bit AND instead of logical one could provide SOME sort of workaround, however ideally I am looking for a solution that does not require ANY CHANGES in the source code. Both due to formal and technical reason (as i mentioned system is big and we have whole process of promoting and deploying code between staging areas and getting sign-offs). And this is for testing only, production version needs to have lazy evaluation enabled (i.e. use &&)
POST-MORTEM:
- "Correct" answer is: No, there is not.
- "Useful" answer: you can change && to &
- "What I did in the end" answer: debug system remotely, put breakpoint on expression and told eclipse to run e() -_-
回答1:
There is no compiler or JVM option for changing the semantics of boolean expression evaluation.
If you cannot modify the source, possible (albeit not guaranteed) options include:
- Creatively recreate the conditions you seek to test via elaborate setup of preconditions.
- Use mock objects.
- Hack the compiler.
- Hack the JVM.
- Twiddle the byte code.
Sorry, those are all much more difficult than a compiler/JVM option or modifying the source. Further, the last three options (as well as the requested compiler/JVM option or modifying the source) violate proper testing protocol of not modifying what's being tested.
回答2:
In order to disable short-circuit use single '&' or '|' rather than two:
boolean ret = a() & b() & c() & d() & e();
回答3:
The single & advice is excellent - to explain why it works:
boolean ret = a() && b() && c() && d() && e();
This call is using Logical And on the returned values from the methods. It knows that if any of the results is false then the final result is false so it can return immediately. 'Lazy evaluation' is a standard computing optimization to avoid doing un-needed processing.
boolean ret = a() & b() & c() & d() & e();
This is replacing the logical operation with an arithmetic one - the bitwise operator. If this was working on integers then it would and
all the individual bits of the integers together. In the case of a boolean though there are only true or false values but it is still evaluated as an arithmetic expression and hence all parts of the expression are evaluated.
So for boolean values & and && give the same logical result, but they are processed differently internally, which happens to give the behavior you are looking for.
来源:https://stackoverflow.com/questions/20422793/is-there-a-way-to-disable-short-circuit-evaluation-in-java