TS/JS Best Practices - Call Site Friendly Parameters
When designing API methods, it's not just about making the method itself readable the call sites should be just as clear! Ideally, developers should understand what a function does without needing to check its definition.
💡 Avoid patterns that reduce readability and maintainability:
❌ Primitive parameters (especially boolean & number arguments)
❌ Multiple same-type parameters (leading to confusion)
❌ Too many optional parameters (forcing undefined values)
🔍 Problematic Examples:
👇 Boolean parameters lack clarity:
👇 Number parameters can be ambiguous:
👇 Multiple same-type parameters make it unclear what each value represents:
✅ Better Approaches:
📌 Options bag
Recommended by LinkedIn
Improves readability and makes parameter order irrelevant:
📌 Two differently named functions
Instead of relying on boolean parameters:
📌 Two-value enum
Explicit and self-documenting:
🎯 Considerations:
🔹 Are these truly separate functions? If the two modes are implemented in very different ways (e.g., they each delegate to separate private functions or have distinct logic paths), then defining them as separate functions is the better choice.
🔹 How many boolean parameters are involved? If you have two or more boolean parameters, multiple named functions may not scale well. Instead, an options bag or an enum can be more effective. If some combinations are invalid, an enum restricting inputs to valid ones can help.
🔹 Verbosity of the function definition An options bag is almost as concise as using a boolean parameter. However, defining separate functions or using an enum can make the function definition longer. If separate functions still delegate to a shared private method with a boolean parameter, the verbosity becomes a drawback.
🔹 Impact on code size If minimizing code size is a priority:
#FrontendDevelopment #WebDev #TypeScript #CodeQuality