r/javascript • • Feb 20 '18

Optional Chaining may be coming to JavaScript

https://dev.to/sammyisa/optional-chaining-may-be-coming-to-javascript--4ff0
321 Upvotes

100 comments sorted by

View all comments

19

u/phpdevster Feb 20 '18 edited Feb 21 '18

I don't mind this coming to JS since different tools for different jobs and all that, but it's been my experience that if you have to do this extensively, you have some design problems with your code whereby objects may or may not be in a reliably complete state at a given time. It means you either have the wrong abstractions, the wrong data models, are grotesquely violating the Law of Demeter, or are assembling data models at the wrong points in your codebase.

Your goal should be to design your domain and application such that you are always working with proper, well formed objects that do in fact have the data and properties you expect them to have. If you only need partial data from a model and don't want to have to populate the whole thing, then your data model is too tightly coupled to too many responsibilities and you should break it apart. If a function is asking such a deep chain of data, then stop passing in the root and pass in only the leaf that you need. If you are doing logic based on the existence or non-existence of some data in an object, stop and more carefully think about the responsibilities of the functions you're passing the potentially incomplete data into.

As convenient as foo?.bar?.baz?.() is, it's really hiding a code smell. At least before when you did all that explicit null checking, you had to stop and think if that was really the right design for the code, and that maybe something was amiss.

2

u/dphrageth Feb 21 '18

I think you're definitely hitting on something. I'm at the start of a code rework and knew that in the code there were a few, legitimate IMO, uses of this nested object checking that at the time I worked carefully to ensure were legitimate and not bad design, but I was excited to replace them with something more convenient.

But as I started coding I completely and inappropriately started dropping this new syntax in everywhere because I wanted to. It does make it slightly too easy, especially because it looks so similar to a regular nested accessor. That said, still looks/functions well where rarely required.

But this is where we can actually flip this in a positive manner. This syntax + a warn lint rule == even better than before. Looks beautiful AND forces me to think it through before I lint-disable that warn.