Logging true condition of big if(.. || ..) statement

Issue

I use Java and I want to determine in logs which statement caused the condition to be true. I have got big if with a lot of ORs. Something like below:

if (StringUtils.isTrue(foo.getArg1)
    || StringUtils.isTrue(foo.getArg1)
    || StringUtils.isTrue(foo.getArg2)
    || foo.getArg3.equals("T")
    || foo.getList1.isEmpty()
    || //and so on...) {
       return true; }

and i would like to get something like:

if (StringUtils.isTrue(foo.getArg1)) {
   log.info("Arg1 made statement true")
          return true;
   }

if (StringUtils.isTrue(foo.getArg2)) {
   log.info("Arg2 made statement true")
          return true;
   }

if (foo.getList1().isEmpty()) {
   log.info("List1 made statement true")
          return true;
   }   //etc...

Is there any tricky way to get effect like this in more generic way, without a lot of if statements ?

Solution

You can have a helper logger method that writes a given message to the log if the boolean passed to it is true:

public boolean static logIfTrue (boolean value, String msg) {
    if (value) {
        log.info(msg);
    }
    return value;
}

And use it:

return logIfTrue(StringUtils.isTrue(foo.getArg1),"Arg1 made statement true") ||
       logIfTrue(StringUtils.isTrue(foo.getArg2),"Arg2 ...") ||
       logIfTrue(foo.getArg3.equals("T"),"...") ||
       logIfTrue(foo.getList1.isEmpty(),"...") ||
       //and so on...;

Answered By – Eran

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published