No one likes those big articles - that’s why we’re creating Quick Tips - short tips to change your developer's life from the moment you read them.
Your function receives many arguments and it’s hard to remember the order or not clean to scale up.
You may also have problems with optional arguments.
You may have started with a small function but over time maybe you’ve added additional flags for some features?
Combine arguments in and object
You may think it looks the same - however...!
- You don’t have to remember the order of the arguments.
- It’s easy to scale.
- In case one of your arguments is optional, you won’t end up in calling
printCustomerDetails('John', 'Doe', someValue, undefined, undefined, false, true)(undefined values just because you want to reach the nth argument).
- If your IDE is not helping with argument names – you won’t have to remember what the 3rd argument was for. Was it
This is also helpful for components (regardless of the framework - although the example is in React), as it’s easier to change an interface (especially if you have some prop drilling) than to modify your property definitions.
Rather than passing property after property...
...pass an object containing all your props.
Guidelines when to use:
- If you have a common data model.
- For options/configuration objects - to allow optional options.
- In a function - if you have more than 5 arguments.
- In a component - when your component takes many properties from a single data model.
If you’re passing more than 5 arguments to a func/comp… you are probably doing something wrong and breaking the SOLID rule. Are you sure your method follows SRP?
More posts by this author