Code Smell 149 - Optional Chaining

Photo by engin akyurt on Unsplash

Code Smell 149 - Optional Chaining

Maxi Contieri
·Jul 16, 2022·

2 min read

Subscribe to my newsletter and never miss my upcoming articles

Play this article

Table of contents

  • Problems
  • Solutions
  • Context
  • Sample Code
  • Detection
  • Tags
  • Conclusion
  • Relations
  • More Info
  • Credits

Our code is more robust and legible. But we hide NULL under the rug

TL;DR: Avoid Nulls and undefined. If you avoid them you will never need Optionals.

Problems

Solutions

  1. Remove nulls

  2. Deal with undefined

Context

Optional Chaining, Optionals, Coalescence, and many other solutions help us deal with the infamous nulls.

There's no need to use them once our code is mature, robust, and without nulls.

Sample Code

Wrong

const user = {
  name: 'Hacker'
};

if (user?.credentials?.notExpired) {
  user.login();
}

user.functionDefinedOrNot?.();

// Seems compact but it is hacky and has lots
// of potential NULLs and Undefined

Right

function login() {}

const user = {
  name: 'Hacker',
  credentials: { expired: false }
};

if (!user.credentials.expired) {
  login();
}

// Also compact 
// User is a real user or a polymorphic NullUser
// Credentials are always defined.
// Can be an instance of InvalidCredentials
// Assuming we eliminated nulls from our code

if (user.functionDefinedOrNot !== undefined) {  
    functionDefinedOrNot();
}

// This is also wrong.
// Explicit undefined checks are yet another code smell

Detection

[X] Automatic

This is a Language Feature.

We can detect it and remove it.

Tags

  • Null

Conclusion

Many developers feel safe polluting the code with null dealing.

In fact, this is safes than not treating NULLs at all.

Nullish Values, Truthy and Falsy are also code smells.

We need to aim higher and make cleaner code.

The good: remove all nulls from your code

The bad: use optional chaining

The ugly: not treating nulls at all

Relations

More Info

WAT?

Credits

Photo by engin akyurt on Unsplash


He who fights with monsters might take care lest he thereby become a monster. And if you gaze for long into an abyss, the abyss gazes also into you.

Nietzsche


This article is part of the CodeSmell Series.

 
Share this