Represent optionality
Use nil (i.e. ()
) to represent optional values.
Note: Use
()
instead ofnull
unless it’s in a json context.
Example 1:
Use nil
to indicate the unavailability of value.
Bad Code
type Employee record {
string middleName = ""; //middleName is not specified
};
Good Code
type Employee record {
string? middleName = ();
};
Example 2:
Return nil
to indicate the unavailability of value.
Bad Code
function getMarks(string name) returns int {
if marks.hasKey(name) {
return marks.get(name);
}
return -1;
}
Good Code
function getMarks(string name) returns int? {
if marks.hasKey(name) {
return marks.get(name);
}
return ();
}