Skip to content

Latest commit

 

History

History
115 lines (60 loc) · 4.44 KB

File metadata and controls

115 lines (60 loc) · 4.44 KB

Code Smell 212 - Elvis Operator

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.

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.

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

Relations

Code Smell 149 - Optional Chaining

Code Smell 06 - Too Clever Programmer

Code Smell 12 - Null

Code Smell 140 - Short Circuit Evaluation

More Info

Wikipedia

Null: The Billion Dollar Mistake

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

Software Engineering Great Quotes


This article is part of the CodeSmell Series.

How to Find the Stinky Parts of your Code