fs: refactor to use optional chaining#36524
Conversation
aduh95
left a comment
There was a problem hiding this comment.
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/ |
jasnell
left a comment
There was a problem hiding this comment.
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 <[email protected]> Reviewed-By: James M Snell <[email protected]> Reviewed-By: Trivikram Kamat <[email protected]>
|
Landed in 54e763d |
PR-URL: #36524 Reviewed-By: Antoine du Hamel <[email protected]> Reviewed-By: James M Snell <[email protected]> Reviewed-By: Trivikram Kamat <[email protected]>

Checklist
make -j4 test(UNIX), orvcbuild test(Windows) passes