Handle Nil values
Use the Elvis operator with proper default values or use errors when returning.
Elvis operator is a conditional operator that can be used to handle nil values. It evaluates an expression and, if the value is nil, executes the second expression. The Elvis operator takes two operands and uses the ?:
symbol to form them.
Example 1:
Bad Code
int? age = ();
int validAge = <int>age;
Good Code
int? age = ();
int validAge = age ?: 0;
Example 2:
Bad Code
string? name = ();
string validName = name.toString();
Good Code
string? name = ();
string validName = name ?: "";
Example 3:
Bad Code
function getUsers() returns string[] {
string[]? users = loadUsers();
if users is string[] {
return users;
}
return [];
}
function loadUsers() returns string[]? {
//loading user code from DB or file etc
}
Good Code
Refer to the following options. We can use the elvis operator or can return error by explicitly checking for nil
. Checking for nil is better than returning unrealistic default value in most cases.
Option 1:
function getUsers() returns string[] {
string[]? users = loadUsers();
return users ?: [];
}
Option 1:
function getUsers() returns string[]|error {
string[]? users = loadUsers();
if users is () {
return error("Error in loading users");
}
return users;
}