Destructuring in func params not good practice?

I wanted to start a discussion on this and see what people thought.

It’s pretty important to me that my code is legible, so that anyone else looking at it can make sense of it as quickly as possible. I do this because I know how much it sucks to be brought into a position where you have to work with someone else’s code, and it’s a total disaster.

So I was writing this:

function mapStateToProps({auth}) {
  return {auth}
}

And got to thinking about using destructuring in the function params. I’m all for shorthand, but imagine someone reading this who may not be familiar with Redux. By specifying the function param as {auth}, you’re not giving any context as to what that parameter is. auth could be a property on any old object, whereas this is much more clear:

function mapStateToProps(state) {
  return {auth: state.auth}
}

Ah, now we know what that argument is! I realize names are just names, and we could’ve said function mapStateToProps(kaboom), but my goal is to have the code self-document in a way.

Another example:

someFunc = ({coords, radius}) => doThingsWith(coords, radius);

This raises questions like, what do the coordinates and radius belong to? A user’s location? Some other location? Now compare to:

someFunc = (destinationObject) => {
  const {coords, radius} = destinationObject;
  doThingsWith(coords, radius);
};

For those who care about code legibility, what’s your take on this?

I think you’re missing an example - a function with multiple ordered arguments. Once your function has 2 or more arguments, I think it’s a good idea to combine them into an object and then use destructuring to get keyword args.

I agree that in the cases you’re talking about, where the argument is one object with some properties, destructuring can be less clear.

Actually, I find the examples with destructuring more clear. With destructuring I know what the expected object argument is just by looking at the function signature. In the second example I have to look at the function implementation to know what the object I pass into the function should look like.

4 Likes

I agree with @seba and destructuring help us to self document function arguments. And it’s looks pretty :slight_smile:

1 Like