DEV Community

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

When & why should "destructuring object methods" be preferred?

nombrekeff profile image Manolo Edge ・2 min read

When and why should this (destructuring object methods) be prefered:

const { getName } = getUser(...);
const username = getName();

Over this (accessing methods on object itself):

const user = getUser(...);
const username = user.getName();

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 username1 = getName1();
const username2 = getName2();

but IMO, it makes it way messier and more confusing than just doing:

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

const username1 = user1.getName1();
const username2 = user2.getName2();

Reduced/missing context

Another issue I see is, it removes/reduces the context from the method. We now need to look where setName has been defined to know where it came from and what it affects, making it harder to keep track.

Take this example:

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

// In another part of the file

setName('Babatunde'); // Where the F**k did `setName` come from 

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

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

const currentUser = getUser(...);

// In another part of the file


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

I tend to use destructuring for parameters, but not for methods.

I know this is common practice in React and such. But outside React, when & why should it be used? Is it a personal preference? Or are there any benefits with this approach?

I'd love to hear what you DEVs have to say about it ❤️


Editor guide