One of my favorite features in Groovy is its hip ?
operator, which facilitates Nullpointer
navigation safety– while this feature isn’t available directly in Java, there is a handy Java operator that I’ve found myself using more and more these days (in Java, man) based upon my dynamic language conditioning of preferring code terseness: the ternary operator.
The ternary operator doesn’t directly relate to the ?
operator in Groovy; however, its bag is similar– that is, reducing typing. This operator enables you to succinctly assign a value to a variable based on one or more boolean decisions like so:
this.location = (location != null ? location : DEFAULT_LOC_NAME);
In the code above, the location
member variable (this.location
) is being set to a location
local variable or a static constant (DEFAULT_LOC_NAME
) if the location
local variable is null
. Thus, the code to the left of the ?
operator must be a boolean
expression and the value to the left of the :
operator is returned if true
and the value to the right of the :
is returned if the expression is false
.
The single line of Java code facilitated by the ternary would be roughly equivalent to a conditional like so:
if(location != null){
this.location = location;
}else{
this.location = DEFAULT_LOC_NAME;
}
Of course, the {}
’s are optional (thus, the code could be reduced somewhat); however, the point being that a copasetically placed ternary reduces typing and a bit of redundancy (in this case), baby.
In the past, I used to eschew the ternary due to its terseness– I found myself using conditionals to more clearly express my intent; however, after years of dynamic language conditioning, I’ve found myself reserving my stance on the ternary.
If you find yourself typing too much Java, baby, then consider employing the ternary– you may find its laconic nature refreshingly simple. Can you dig it, man?