-
Notifications
You must be signed in to change notification settings - Fork 29.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
fs: refactor to use optional chaining #36524
Conversation
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
object?.method?.()
is equivalent to if(object && object.method) object.method()
, not if(object) object.method()
. I think we should not add extra checks to avoid behaviour changes, and it might impact perf.
f9d9035
to
8b71da7
Compare
Yes, thanks for the guidance. |
Nevermind.. looks like @mscdex beat me to it. There was a benchmark job running already but I hadn't noticed that it was for the same PR. https://ci.nodejs.org/view/Node.js%20benchmark/job/benchmark-node-micro-benchmarks/759/ |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Performance benchmark results look good! Happy to see us start to make these changes. The one downside is that it'll make backporting a bit more difficult
Yes, and this will make our code easier to read. And I have two questions and would like to know what you think.
|
Incremental changes are best. And no, backporting shouldn't hold this up. |
I know what to do now, thanks for your guidance. |
I disagree :) |
When there is a difference of opinion on code style, I think we should look at what the community thinks.
This results in shorter and simpler expressions when accessing chained properties when the possibility exists that a reference may be missing.
// Error prone-version, could throw.
const nameLength = db.user.name.length;
// Less error-prone, but harder to read.
let nameLength;
if (db && db.user && db.user.name)
nameLength = db.user.name.length;
// The above can also be expressed using the ternary operator, which doesn’t exactly help readability
const nameLength =
(db
? (db.user
? (db.user.name
? db.user.name.length
: undefined)
: undefined)
: undefined);
// Still checks for errors and is much more readable.
const nameLength = db?.user?.name?.length; |
PR-URL: #36524 Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com> Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Trivikram Kamat <trivikr.dev@gmail.com>
Landed in 54e763d |
PR-URL: #36524 Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com> Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Trivikram Kamat <trivikr.dev@gmail.com>
Checklist
make -j4 test
(UNIX), orvcbuild test
(Windows) passes