DEV Community

loading...

Discussion on: 😲🤯The most outstanding new feature in Javascript you need to know about: Optional Chaining

Collapse
svitekpavel profile image
Pavel Svitek

This is probably the worst proposal ever. It will allow to write even shittier code in JS.

Rather than solving the problem by better code design, devs will use this crappy shit.

Collapse
lampewebdev profile image
Michael "lampe" Lazarski Author

Okay, why is this crappy?

What do you mean with better code design?

Please explain a little bit more what you mean.

Collapse
svitekpavel profile image
Pavel Svitek

You are retrieving some data from API. Till you retrieve the data, you should have something like data: null, after you get data from API, you should have the whole object.

API should always return you a predefined object structure, right? So once data !== null, you should be able to access all properties and deep properties instead of checking every object in your structure.

I understand that there might be some valid cases where object?.property?.property might be a shorter code, but it doesn't mean it should be implemented in the language.

Once this is in language, the syntax will be overused and more shitty code will be written.

Thread Thread
lampewebdev profile image
Michael "lampe" Lazarski Author

What if the API is not in your hand and you have no control over it?

I don't see it being overused in ruby or c# or any other language. Why should this happen in JS?

Thread Thread
sudojoe profile image
Joseph Locke

Assuming that objects returned from third-parties conform to a specific structure (and therefore, not 'verifying' their structure and the presence/lack-thereof of expected properties) is most-likely a security blunder.

Thread Thread
lampewebdev profile image
Michael "lampe" Lazarski Author

Sorry, I don't fully understand what you mean.

Collapse
thewix profile image
TheWix

A better pattern would be to use Option/Maybe or Either.

If I have something like:

var a = null;

rather than using a?.b I would use:

const a = fromNullable(a);

const aValue = a.map(_ => _.b).getOrElse("No value");

You can further chain like

a.chain(_ => .b)
.chain(
=> .c)
.chain(
=> _.d)

In your anti-corruption layer convert all nulls to Option/Maybe and you don't have to deal with nulls.

Thread Thread
lampewebdev profile image
Michael "lampe" Lazarski Author

I would love to not deal with null/undefined in JS.

I find the ?. really elegant.

But I also find Ruby elegant where things like this are normal.