Code Smell 212 - Elvis Operator
Your code is not safer using this operator
TL;DR: Don't propagate nulls.
Harder to read 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.
val shipTo = address?: "No address specified"
val shipTo = if (address != null) address else "No address specified"
// This keeps the billion-dollar mistake error
We can detect this operator usage and replace them with more strict checks.
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.
When the left hand side is true, the right hand side is not even evaluated; it is "short-circuited." This is different than the behavior in other languages such as C/C++, where the result of || will always be a boolean.
Code Smells are my opinion.
You can't communicate complexity, only an awareness of it.
This article is part of the CodeSmell Series.