Overloading
Origin: semantic overloading
In linguistics, semantic overload
occur when a word or phrase more than one meaning.
- It is used in ways that convey meaning based on its divergent constituent concepts.
What is function or method overloading
Ability to create multiple functions of the same name with different implementations.
- Allowing one function to perform different tasks depending on context.
- Overloading is a form of
polymorphism
.
Implementation
function getInfo(value: string | number): string | number { if (typeof value === "string") { return `Hello, ${value}!`; } else if (typeof value === "number") { return value * value; } // handle unexpected types throw new Error("Invalid type"); }
Usage
// overload (good), same function names function Person[] FindPersons(string nameOfPerson) { ... } function Person[] FindPersons(date dateOfBirth) { ... } function Person[] FindPersons(int age, string dogsName) { ... } // non-overloading unique functions (bad) function Person[] FindPersonsByName(string nameOfPerson) { ... } function Person[] FindPersonsByDOB(date dateOfBirth) { ... } function Person[] FindPersonsByAgeAndDogsName(int age, string dogsName) { ... }
Tradeoff
You get consistency in naming, but at the cost of ambiguity about exact implementation.
Why use it
- Improve readability of code.
- It allows the programmer to write functions to do conceptually the same thing on different types of data without changing the name.
- Your function may want to work with some optional details.