DEV Community

Cover image for Code Smell 149 - Optional Chaining
Maxi Contieri
Maxi Contieri

Posted on • Originally published at maximilianocontieri.com

Code Smell 149 - Optional Chaining

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (29)

Collapse
 
loucyx profile image
Lou Cyx •

This is your opinion, and is ok ... my problem is mainly that is presented as fact, when it isn't.

// I agree that we should avoid "falsy" values, so for that you can just combine
// optional chaining with nullish coalescing and default to `false` if the value
// is `undefined`, making the value always an actual boolean.
if (user?.credentials?.notExpired ?? false) {
    user.login();
}

// This is also ok, if the function exists you call it, if it doesn't, you don't.
user.functionDefinedOrNot?.();

// If the function returned a value, then ideally you should use nullish
// coalescing again.
const value = user.functionDefinedOrNot?.() ??