Code Smell 212 - Elvis Operator

Photo by Susan Mohr on Unsplash

Code Smell 212 - Elvis Operator

Your code is not safer using this operator

TL;DR: Don't propagate nulls.

Problems

  • NULL propagation

  • Harder to read code

  • Hacky code

Solutions

  1. Remove the nulls.

  2. If you can't remove it, deal explicitly with them.

Context

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.

Sample Code

Wrong

val shipTo = address?: "No address specified"

Right

val shipTo = if (address != null) address else "No address specified"

// This keeps the billion-dollar mistake error

Detection

[X] Automatic

We can detect this operator usage and replace them with more strict checks.

Tags

  • Null

Conclusion

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 than the behavior in other languages such as C/C++, where the result of || will always be a boolean.

Relations

More Info

Disclaimer

Code Smells are my opinion.

Credits

Photo by Susan Mohr on Unsplash


You can't communicate complexity, only an awareness of it.

Alan Perlis


This article is part of the CodeSmell Series.