Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test only if variable is not null in if statement

I have the following method where I want to test the event.status property only if status has been passed in:

def findEvent(String desc, String status = null, Collection events) {
        return events.find {
            it.description == desc && \\If status is not null: it.status == status
        }

        throw new Exception("Review Event Record Not Found: ${desc}")
}

I thought it could be done like this, but it doesn't seem to work:

def findEvent(String desc, String status = null, Collection events) {
        return events.find {
            it.description == desc && (status != null ?: {it.status == status})
        }

        throw new Exception("Review Event Record Not Found: ${desc}")
}

Is there any way this could be done? Or do I have to go back to something like this:

if (status != null) {
    return events.find {
        it.description == desc && it.status == status
    }
} else if (status == null) {
    return events.find {
        it.description == desc
    }
}

Is there some kind of best practice?

like image 818
Matthew Brown Avatar asked Jun 12 '12 01:06

Matthew Brown


People also ask

IS NOT NULL if statement?

The IS NOT NULL condition is used in SQL to test for a non-NULL value. It returns TRUE if a non-NULL value is found, otherwise it returns FALSE. It can be used in a SELECT, INSERT, UPDATE, or DELETE statement.


1 Answers

I don't believe the expression is sensical as it is.

Elvis means "if truthy, use the value, else use this other thing."

Your "other thing" is a closure, and the value is status != null, neither of which would seem to be what you want. If status is null, Elvis says true. If it's not, you get an extra layer of closure.

Why can't you just use:

(it.description == desc) && ((status == null) || (it.status == status))

Even if that didn't work, all you need is the closure to return the appropriate value, right? There's no need to create two separate find calls, just use an intermediate variable.

like image 140
Dave Newton Avatar answered Sep 22 '22 22:09

Dave Newton