Your code is not safer using this operator
TL;DR: Don't propagate nulls.
-
NULL propagation
-
Harder to read code
-
Hacky code
-
Remove the nulls.
-
If you can't remove it, deal explicitly with them.
The Elvis operator is also known as the null-coalescing operator or the null-safe operator.
It is a shorthand operator used in some programming languages to simplify null-checking.
The Elvis operator takes the form of ?. and is used to access a property or method of an object only if that object is not null.
If the object is null, the operator returns null without attempting to access the property or method, thus avoiding a potential null reference exception.
The nickname "Elvis operator" originated from the visual resemblance of the operator to the famous singer Elvis Presley's hairstyle.
The symbol "?:", with its round shape on top and a curl underneath, vaguely resembles the pompadour hairstyle that Elvis Presley was known for.
val shipTo = address?: "No address specified"
val shipTo = if (address != null) address else "No address specified"
// This keeps the billion-dollar mistake error
[X] Automatic
We can detect this operator usage and replace them with more strict checks.
- Null
The code can be difficult to follow and may require additional comments or explanations to make it clear what is happening.
The operator hides potential errors or bugs in the code.
For example, if an object is null and the Elvis operator is used to return a default value, this may mask the fact that there is a problem with the code that is causing the object to be null in the first place.
In several languages, such as Common Lisp, Clojure, Lua, Object Pascal, Perl, Python, Ruby, and JavaScript, the OR operator (typically || or or) has the same behavior as the above: returning its first operand if it would evaluate to true in a boolean environment, and otherwise evaluating and returning its second operand.
When the left-hand side is true, the right-hand side is not even evaluated; it is "short-circuited." This is different from the behavior in other languages such as C/C++, where the result of || will always be a boolean.
Code Smell 149 - Optional Chaining
Code Smell 06 - Too Clever Programmer
Code Smell 140 - Short Circuit Evaluation
Null: The Billion Dollar Mistake
Code Smells are my opinion.
Photo by Susan Mohr on Unsplash
You can't communicate complexity, only an awareness of it.
Alan Perlis
Software Engineering Great Quotes
This article is part of the CodeSmell Series.