We have a POJO in our Java application let's say Request
which has validateRequest() method that basically validates some of it's fields using Guava's Preconditions library.
So, Basically Class looks like this :
public class Request {
private Integer field1;
private String field2;
.
.
private String fieldN;
public String validateRequest() {
try {
Preconditions.checkArgument( getField1() >= 0, "error message" );
Preconditions.checkArgument( StringUtils.isNotBlank(getField2()), "error message" );
.
.
} catch (IllegalArgumentException | NullPointerException e){
//emit some metric
return e.getMessage();
}
return null;
}
}
We call the below method in all the flows after building the Request POJO.
public void someMethod(Request request) {
String message = request.validateRequest();
if(message!= null)
throw new Exception(message);
}
In some of the flows in our application we are never initialising field1 and field2 , so they are always null in those flows. So, ideal expectation is that validateRequest should return error message for those flows. But, what we notice is production is that this application never returns error message. It is as if Preconditions are never executed! Even metric that we emit is zero. On searching web, found out that compiler's optimisation can cause certain validation/assertion statements to be ignored, but didn't get more details around it.
When we explicitly remote debug to our Production box and put break-point on precondition statements they get executed and error message is returned and metric is emitted.
When we deploy this same application is deployed on Stage, code behaves as expected and throws validation error and metric is emitted.
Want to understand if compiler optimisation is the culprit here, or if root cause could be something else. How to verify that compiler optimisation is causing Preconditions to be ignored?