简体   繁体   中英

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

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.

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.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM