clean-code-typescript icon indicating copy to clipboard operation
clean-code-typescript copied to clipboard

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

Open bluEEil opened this issue 3 years ago • 1 comments

`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?

bluEEil avatar Apr 14 '21 11:04 bluEEil

@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 avatar Apr 26 '22 07:04 dimadeveatii