Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

"Set default objects with Object.assign or destructuring" - destructing example might be bad practice? #46

Closed
bluEEil opened this issue Apr 14, 2021 · 1 comment
Labels
question Further information is requested

Comments

@bluEEil
Copy link

bluEEil commented Apr 14, 2021

`type MenuConfig = { title?: string, body?: string, buttonText?: string, cancellable?: boolean };

function createMenu({ title = 'Foo', body = 'Bar', buttonText = 'Baz', cancellable = true }: MenuConfig) {
// ...
}

createMenu({ body: 'Bar' });`

Crossing the example given in "Set default objects with Object.assign or destructuring" with one of the first rules:
"Function arguments (2 or fewer ideally)
Limiting the number of function parameters is incredibly important because it makes testing your function easier. Having more than three leads to a combinatorial explosion where you have to test tons of different cases with each separate argument."

Isn't this example actually crossing the line of having more than 3 arguments? Logically I feel like the destructing example is with object with more than 3 properties is the same as giving the function more than 3 arguments for the exact same reason specified in this rule. Am I wrong to think this way?

@dimadeveatii
Copy link
Member

@bluEEil sometimes functions require more than 3 arguments to cover the logic. In that case making it cleaner means defining a type that groups all arguments together and make the function accept fewer arguments.

In the mentioned example, technically, it is still just one argument, but it's a type with 4 fields. What's really important is that all the fields in the type are highly cohesive. Therefore, when a function must accept more than 3 arguments, we usually define a type/interface for that.

Imagine another use case, where you have a save(user: User) function. The User type might have fields like firstName, lastName, email, age, profilePage, role etc. This is still good and clean, much better than having saveUser(firstName: string, lastName: string, email: string, age: number, role: Role)

@dimadeveatii dimadeveatii added the question Further information is requested label Apr 26, 2022
@dimadeveatii dimadeveatii closed this as not planned Won't fix, can't repro, duplicate, stale Jan 9, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
Projects
None yet
Development

No branches or pull requests

2 participants