DEV Community

Cover image for When & why should object destructuring be preferred?
Keff
Keff

Posted on • Edited on

When & why should object destructuring be preferred?

When and why should destructuring object methods be prefered:

const { getName } = getUser(...);
const username = getName();
Enter fullscreen mode Exit fullscreen mode

Over accessing methods on object itself:

const user = getUser(...);
const username = user.getName();
Enter fullscreen mode Exit fullscreen mode

I see some "issues" with the first approach

What happens if we want to have multiple users?
We can rename them:

const { getName: getName1 } = getUser(...);
const { getName: getName2 } = getUser(...);

const name1 = getName1();
const name2 = getName2();
Enter fullscreen mode Exit fullscreen mode

but IMO, it makes it harder to follow, than just doing:

const user1 = getUser(...);
const user2 = getUser(...);

const name1 = user1.getName();
const name2 = user2.getName();
Enter fullscreen mode Exit fullscreen mode

Because it removes some of the context (or information) from the method. We need to look where setName has been defined to know what it does, needing to scroll up or following the code to where it was defined, making it harder to keep track.

Take this example:

const { setName } = getUser(...);

...
// In another part of the file
...

setName('John'); // Where did `setName` come from? 
Enter fullscreen mode Exit fullscreen mode

In this scenario, we must have a mental map of where setName came from and what it will affect.

Yeah sure, if it's our own code and we work on it often it will not be that big of an issue, as we will have a good mental map of the code. But imagine you work with more people, or come back to the code 1 year later...

BUT if we do it as follows, we preserve some context:

const currentUser = getUser(...);

...
// In another part of the file
...

currentUser.setName('Babatunde');
Enter fullscreen mode Exit fullscreen mode

With this approach, we know that setName affects the currentUser object. Reducing the mental map needed and making it easier to follow and understand.


What's your take on this?

Top comments (0)