Why overloaded methods defined in OOPS?

Viewed 315

Interviewer had asked me what is method overloading and I had given answer saying, method overloading is within same class where two or more methods have same name but different signature, with following example -

//method with two parameters
public int add(int a, int b){
  return a + b;
}

//method with three parameters    
public int add(int a, int b, int c){
  return a + b + c;
}

To this example, he said why do we need two methods with same name i.e. add. Instead we can have two methods with different names i.e. addTwoNumbers and addThreeNumbers which indicates, method names are more verbose and if we follow this approach, we don't need method overloading. (And same is true for other Java apis where method overloading is used.)

Considering his above thought, he asked why OOPS principle still have method overloading and why is being used so intensively? What is intention of inventors to introduce concept of method overloading?

6 Answers

Considering his above thought, he asked why OOPS principle still have method overloading and why is being used so intensively? What is intention of inventors to introduce concept of method overloading?

First of all, overloading is not related to OOP. From Programming -- Principles and Practice Using C++ by Bjarne Stroustrup:

The use of inheritance, run-time polymorphism, and encapsulation is the most common definition of object-oriented programming.

Note that overloading is not one of the key principles of OOP.

Now if we come to overloading, then the logic to support it is to make the code readable (though it can be considered as opinion based). For example, C has following functions:

int abs(int j);
long int labs(long int j);
double fabs(double x);
float fabsf(float x);

But C++ has overloaded version of abs with different types (C++ still support C functions for backward compatibility though). Instead of inventing new names for same functionality with different types, it is easier and more readable if compiler itself can differentiate among functions with same name but different types, i.e. overloaded functions. This is also known as static polymorphism as the comment from @Basilevs pointed.

We can get the intention of Bjarne Stroustrup, the creator of C++, from his book The Design and Evolution of C++. According to him, several people wanted operator overloading but he was initially reluctant as:

  1. It was hard to implement.
  2. It was hard to teach and hard to define precisely.
  3. Code using operator overloading was reputed to be inefficient.
  4. It was reputed to make the code incomprehensible.

However if those problems could be solved then it could solve some real problem and many people wanted that support. He eventually overcame these problems and overloading became a part of C++. From the book:

However, if all of these conjectures were false, overloading would solve some real problems for C++ users. There were people who would like to have complex numbers, matrices, and APL-like vectors in C++. There were people who would like range-checked arrays, multidimensional arrays, and strings. There were at least two separate applications for which people wanted to overload logical operators such as I (or), & (and), and A (exclusive or). The way I saw it, the list was long and would grow with the size and the diversity of the c++ user population. My answer to [4], "overloading makes code obscure," was that several of my friends, whose opinion I valued and whose experience was measured in decades, claimed that their code would become cleaner if they had overloading. So what if one can write obscure code with overloading? It is possible to write obscure code in any language. It matters more how a feature can be used well than how it can be misused.

The related portion(page 78) is available in Google Books for free preview. Please have a look into it for more detailed discussion.

Though this was the design decision made by the inventor of C++, I think similar rationally applies to other languages too.

In my opinion it was introduced in order to avoid any confusion. Since both the methods performs same operation it might be easy for a programmer to search for the same method name performing the same functionality rather than finding methods with different name performing same functionality.

The main reason behind this is the cleanliness of the code. For example let's take print method in java. It is an overloaded function since it can have different arguements but with same name.

System.out.print(Boolean b),System.out.print(Integer b),System.out.print(String b),System.out.print(Float b) 

etc etc. But all we know is that there is a print method and we have to pass whatever we need to print. Had there not been overloading then the names of the function would look like

 System.out.printBoolean(Boolean b),System.out.printInteger(Integer b),System.out.printString(String b),System.out.printFloat(Float b) 

which not only makes the code complex but also hard to remember which function to call when. Overloading is used when the ultimate goal is same but the path or objects used may be different. In this case our ultimate goal was to print whether it be an integer or string etc.

Why function overloading at all? When action is almost same, just the set of inputs are different.

In Java, using function overloading, we can support the concept of optional parameter (as there is no direct support for it in Java)

String formatStr(String str){   //if you don't care about having a different choice than default
   String defaultPrefix = "__"; 
   return formatStr(str, defaultPrefix); 
}  

String formatStr(String str, String prefix){  //You are free to choose whatever prefix you want.
    return prefix + str; 
}  

Simple answer is because to decrease the code complexity ,because using this technique will be produce the OOP principle of polymorphism (compile time polymorphism also know as static binding).So we know with the aid of polymorphism we can decrease the code complexity because if you have your same behaviours in the code in a single name, this will help the developers to figure it out what's happening in the code much more easily.Otherwise if you name your same kind of behaviours(methods) in different names it will be much harder to understand the code especially for a new developer who is reading your code.

Overloading helps since we have the same method name, but the flexibility to give in different number of parameters. Therefore the programmer need not take a large effort to remember multiple names of different methods. Let's take an example of using petty cash. The petty cash in an office on a daily basis is different. Say a programmer writes a code to calculate the petty cash expenditure on a daily basis. Then as cost changes, because on one day we may have printing cost, stationary costs, on another day traveling costs may also be included, then when number of parameters change, rather than having multiple function names to calculate the petty cash total for the day, with concept of overlaoding, programmer can have the same function/ method name making his or her life much easier.

Related