I've been writing JS almost two decades at this point, but I still can't see why ?. is not the beginning of an anti-pattern, especially for method calls.
I saw the post
And one that caught my eye was number 2 "Optional Chaining with Function Calls":
const user = { getName: () => 'Alice', }; console.log(user.getName?.()); // Alice console.log(user.getAge?.()); // undefined
Which screams "I don't know the interface to my objects, and I don't care."
You definitely should care about the interface to your objects.
I can almost see an argument for robustness if a library API changes, but no, if you're using a library, you know the interface to the objects, fix your code.
It just seems like a massive bug attractor.
You never want something to be undefined. Or have I missed a memo about that?
And that goes double for methods. If two objects don't have the same behaviours, they need to be treated as different types, not just shrugging and saying "it'll be alright".
Is testing for null illegal these days? I know null has been called a billion dollar mistake, but that is solved by an option type (like Maybe in Haskell), not what looks like the inverse.
An option type lets you know that this is something that could be null, so proceed with caution. It doesn't hide the fact, like ?. does.
With all that said, I'm happy to be disabused of the notion that ?. is just kicking the can down the road when it comes to checking for null, or is just bad design when it comes to undefined.
What is a good pattern, i.e. one that reduces bugs, that you can get using ?.?
The above is the detailed content of Explain like Im your junior: why is ?. good?. For more information, please follow other related articles on the PHP Chinese website!