Embracing Null-Handling in Conditions
You can avoid many extra lines of code by understanding how conditional statements behave with null values. If a variable someFlag is a Boolean variable that might be null, then the following conditional block executes only if someFlag is true.
A String
variable can be null
, an empty string
(""
), or can contain at least one character in it. If a variable
middleName
is a String
, then the following conditional
block executes only if middleName
is not null
and contains
at least one character:
// If customer has a middle name...
if (middleName) {
// Do something here if middleName has at least one character in it
}
If a variable recentOrders
is a List
, then the following
conditional block executes only if recentOrders
is not null
and contains at least one element:
// If customer has any recent orders...
if (recentOrders) {
// Do something here if recentOrders has at least one element
}
If a variable
recentTransactions
is a Map
, then the
following conditional block executes only if recentTransactions
is not
null
and contains at least one map
entry:// If supplier has any recent transactions...
if (recentTransactions) {
// Do something here if recentTransactions has at least one map entry
}
If a variable
customerId
can be null
, and its data type is
anything other than the ones described above then the following conditional block executes
only if customerId
has a non-null
value:// If non-boolean customerId has a value...
if (customerId) {
// Do something here if customerId has a non-null value
}
If you need to test a
Map
entry in a conditional and there's a chance the
Map
might be null
, then remember to use the
safe-navigation operator (?.
) when referencing the map key by
name:// Use the safe-navigation operator in case options Map is null
if (options?.orderBy) {
// Do something here if the 'orderBy' key exists and has a non-null value
}