DEV Community

Cover image for Code Smell 212 - Elvis Operator
Maxi Contieri ⭐⭐⭐
Maxi Contieri ⭐⭐⭐

Posted on • Originally published at maximilianocontieri.com

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