DEV Community

Discussion on: 😰 Optional chaining trap !

Collapse
 
thekashey profile image
Anton Korzunov

I hate this pattern. I hate lodash getter, and I hate optional chaining.

You have to answer the question “why” some key is empty, and what you are going to do then - handle the root cause, not the consequences.

Collapse
 
slashgear_ profile image
Antoine Caron

I live in a world where

Everything 👏could 👏be 👏 nullable 👏

I really think that being able to design an application where nothing is null is a utopia.

Collapse
 
woubuc profile image
Wouter • Edited

When you're working with data coming in from an external source (user input, rest api, database, ...) you can never be 100% certain that it won't be null.

Data structures inside your application should indeed be designed to always adhere to the same strict schema, although even that isn't always the case.

Also: that's a very strong reaction to have to a piece of programming syntax.

Collapse
 
elmuerte profile image
Michiel Hendriks

I like the safe navigation operator, but I fear its usage. One level is ok, two might be acceptable, but beyond that you are doing things wrong.

It is nice for templates. But for normal programming? What are you doing so deep in an object structure?

Collapse
 
woubuc profile image
Wouter

I agree, overuse of optional chaining and null-coalescing is something that code styles and guidelines will have to limit.

As I see it, it will mostly be useful for things like options objects loaded from a JSON or YML file, where you have settings that may or may not be set, and often 1-3 levels deep. Or when loading documents from a MongoDB where you have set of properties and data that may or may not be there.

Collapse
 
thekashey profile image
Anton Korzunov

What are you doing so deep in an object structure?

Exactly the point! If a top level key is not accessible, then:

  • why it's not accessible? it is null, undefined, so you can't go deeper, or it string, and your data type is too mutable? It's a quite popular to have something which could be "string/object" or "object/function". Why?
  • then may be another keys from the same location, you are going to read a moment later is also not accessible. Why? May be some decision should be made a bit before? Why?
  • and of course - why some data (you got from the network) might unpredictable not exists, and you are not "ready" for this. Why?
Collapse
 
eddiecooro profile image
Eddie

Because it's some response coming from the server without any type safety, maybe.