What is the use/advantage of function overloading?
Advantages of method overloading in java Method overloading increases the readability of the program. Overloaded methods give programmers the flexibility to call a similar method for different types of data. Overloading is also used on constructors to create new objects given different amounts of data.
When we have multiple functions with the same name but different parameters, then they are said to be overloaded. This technique is used to enhance the readability of the program. Function overloading is normally done when we have to perform one single operation with different number or types of arguments.
The one main advantage of these overriding and overloading is time-saving. Save memory space. The readability of the code is increased. Here, for function overloading concept, we can use different same function names for different operations eliminating the use of different function names.
IMO, the primary benefit is consistency in the naming of methods / functions which logically perform very similar tasks, and differ slightly in by accepting different parameters. This allows the same method name to be reused across multiple implementations.
e.g. The overloads: (Good)
function Person[] FindPersons(string nameOfPerson) { ... } function Person[] FindPersons(date dateOfBirth) { ... } function Person[] FindPersons(int age, string dogsName) { ... }
Are preferable to 'uniquely named' functions: (Worse)
function Person[] FindPersonsByName(string nameOfPerson) { ... } function Person[] FindPersonsByDOB(date dateOfBirth) { ... } function Person[] FindPersonsByAgeAndDogsName(int age, string dogsName) { ... }
This way the coder writing a client which calls / consumes these functions can operate at a higher level of conceptual thinking ("I need to find a person") and doesn't need to remember / locate a contrived function name.
With static typing, the compiler will be left to match the applicable overload based on the usage parameters. For dynamic typing, this same match up will happen at run time, possibly resulting in failure if no appropriate match is found.
Very valid question.
You get consistency in naming, but at the cost of ambiguity about exact implementation.
The real issue is human memory for method names, right? we find it easier to remember names that are commonly used.
and economy of typing, allowing for shorter method names? fewer different names means (mathematically) that the name itself carries less information.
These two issues shouldn't be any concern, with IDEs that find/guess/insert method names rapidly based on the first few characters, and parameter/return types.
But I do think there is a cost, in preciseness of coding, as well as a benefit.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With