Quantcast
Viewing latest article 6
Browse Latest Browse All 10

Method Overloading

One great question on StackOverflow is essentially, “What is method overloading for?” Method overloading, or function overloading, is a feature in some programming languages that allows multiple methods to be made with the same name, but each able to handle different types of input. Method overloading can add expressiveness, conciseness, and awesomeness to any script.

Method overloading, not to be confused with overriding, will look different for each language, and may not be available for some. The essence of it, as mentioned, is to be able to dynamically add methods to an object. In Java, a basic example would look like:

bool add($param1, $param2){
    return true;
}
int add($param){
    return 100;
}
add(2,3); // returns bool, true
add(2); // returns int, 100

This is overloading the return parameters. As you can see, this can come in handy. Perhaps, even more handy and more often used is overloading the in parameters as so:

bool add(){
    return true;
}
bool add(int param){
    return false;
}
bool add(string param1, int param2){
    return true;
}
add(); // returns bool, true
add(1); // returns bool, false
add('name',1); // returns bool, true

And, of course, both techniques can be combined for even greater flexibility. What Java programmers may not know is just how fortunate they are. Other languages, like PHP, require the use of magic methods, such as __set and __get.

Having this ability to overload methods allows for a simple call to a function like add to be much more concise and expressive. There is no longer a need for multiple functions with different names to handle the dynamic input–input of different types as well as different numbers of input parameters. The coding language does it for you. This is perhaps the closest strong typed languages, like Java, can get to weak typed languages like JavaScript. This technique is a tool every programmer using a strong typed language should have.


Viewing latest article 6
Browse Latest Browse All 10

Trending Articles