Why does org.apache.commons.lang.BooleanUtils.isTrue(Boolean bool) use the ternary operator?

StackOverflow https://stackoverflow.com/questions/12836734

  •  06-07-2021
  •  | 
  •  

Question

I F3'd into this for no particular reason, and was surprised to see this method implemented as follows:

public static boolean isTrue(Boolean bool) {
        if (bool == null) {
            return false;
        }
        return bool.booleanValue() ? true : false;
    }

Why not?

public static boolean isTrue(Boolean bool) {
        if (bool == null) {
            return false;
        }
        return bool.booleanValue();
    }

It doesn't really matter, so I wondered is there some benefit to it? Readability is a weak enough argument, I consider this to be noise. Unless there is some other benefit that I am missing.

Was it helpful?

Solution

I can't find any justifiable reason.

The API specification for Java says:

public boolean booleanValue()

Returns the value of this Boolean object as a boolean primitive.

So if our bool object is:

Boolean bool = new Boolean(true);

This is equivalent:

bool.booleanValue() == true;

The ternary comparator here is redundant and decrease the readability.

OTHER TIPS

For sure in your code you have one atomic operation less. See this for good explanation: https://stackoverflow.com/a/493258/1509129

I don't think there's a final answer to why it's written that way, since as Felipe Fernández points out there's no functional reason to do it

However, my guess would be that it's done to make the method symmetric with others in the same class returning Boolean objects, such as toBooleanObject

public static Boolean toBooleanObject(boolean bool) {
        return bool ? Boolean.TRUE : Boolean.FALSE;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top