Frontend Quick Tips #8 Handling Too Many Arguments in a Function
Those may be some patterns explained in JS code on real-life examples or some techniques for better code.
Problem:
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?
Solution:
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
isEmployed
flag?
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.
Important note
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 followsSRP?