4 ms·
that thing about forests and tree. IMHO the problem here is not the destructuring, it's passing a gigantic object to a function when the only important stuff a
by _ZeD_ 4y ago
that thing about forests and tree.
IMHO the problem here is not the destructuring, it's passing a gigantic object to a function when the only important stuff are a pair of leaf nodes.
const Component = (props) => {
console.log(props.a.deeply.nested.variable);
};
In the article the author said that this is a good approach (and there is a second one filled with `?.` between each level
This is a symptom of a bigger problem: what has happened to the Law of Demeter? I think we drop a lot of good practices, when we switched from OOP and "functions + data structures".
- swah 4y agoBut passing the full object is so easy... and works so well most of the time. And with Typescript we know what is there... in theory.
- capableweb 4y agoBut it doesn't signal the original intent and is also reusable in less contexts... Imagine we have the two following objects: const person = {name: "John"} const book = {title: "Bible"} Only one of the following functions tell the user (developer who uses the function) A) what is actually needed for the function to work by just looking at the function signature and B) works for both objects, regardless of where `name` comes from. function sayHello(person) { console.log(`Hello ${person.name}`) } function sayHello(name) { console.log(`Hello ${name}`) } Not to mention, passing smaller things leads to less memory usage, which is generally also a good idea.
- ziml77 4y ago> Not to mention, passing smaller things leads to less memory usage, which is generally also a good idea. It's not using any more memory. Whether you pass in the person object or the string, you're putting a reference on the stack. There will be a slight speedup with the more generic one if you are accessing the name more than once in the function, but you can avoid that by storing the name in a local variable. And picking between the two isn't as straightforward as you make it out. Sure, you make it so any string can go into sayHello, but now you've introduced repetition at the call sites as they each have to pick the correct property to pass in. Also it means you can't easily change the sayHello function to do something like meeting a new requirement that it needs to greet the user more formally. If I take the whole person object, the change can be made in a single spot instead of having to modify the callers: function sayHello(person) { console.log(`Hello ${person.title} ${person.lastName}`); }