Aug 28, 2017 · 1 min read
My mistake. It’s a known code smell but in C#, mainly because default values are constant which is hard coded into compiled calling assemblies:
- Sonar C# Rules 2360 - Optional parameters should not be used
- Guidance for Using Optional and Named Parameters In C# & .NET 4.0
But even in JavaScript, default values should be used with care.
→ Does the function really perform the same task when called with all parameters vs with parameters without default value? Introducing an overload with another name may convey a clearer intent. E.g.:
With default parameters:
const createUser = (name = '', surname = '') => ({ name, surname });
const user = createUser();With overloads, in TypeScript in order to have argument type without default value and built-in required arguments:
const createUser = (name: string, surname: string) => ({ name, surname });
const createEmptyUser = () => createUser('', '');
const user = createEmptyUser();→ What should be done to calling sites when a default value is changed?
- Nothing: let always use the default value?
- Refactor to use the old default value?
- The answer may be difficulted to get in some tricky cases. With overloads with an appropiated name, it should be simpler.
→ Some code smells may appeared:
