overloading

What Is Method Overloading?

overloaded

 

Today I have another exciting post for you on fundamentals. We’ll take a look at Method Overloading in statically-typed, object-oriented languages like C++, C#, and Java. 

Some dynamically-typed programming languages have a similar property, Function Overloading. For example, Python has Function Overloading, but JavaScript does not. In JavaScript, we are allowed to pass a function any number of parameters of any type. 

So, what is Method Overloading?

It’s the ability to create multiple methods with the same name yet different parameter lists and implementations. 

What does that mean? 

I’ll explain Method Overloading with an example.

Say, we have a LogError() method on a Logger class. We use LogError() inside our applications for recording exceptions:

public void LogError(Exception ex)
{
   // Log the error
}

So far, so good. Let’s say we now encountered a new scenario: In a section of workflow code, we have an error situation, but we have no exception. We would still want to log the problem as an error. And we want to give it a descriptive message. We want to call something like 

logger.LogError("Some problem occurred.");

But LogError() already exists and takes an Exception as a parameter, not a string! What are we to do? We could create a new method, LogErrorMessage():

public void LogErrorMessage(string errorMessage)
{
   // Log the error message
}

And that would work just fine. 

I think that there are a few disadvantages to this approach:

  1. The method name is getting long for a public method. Public methods should have short, concise names.
  2. We are coupling our method implementations to the parameter types. If we had another parameter on a third error logging method, would we call it LogErrorWithMessageAndException? Probably not a great idea.
  3. If I saw a LogError() method as well as a LogErrorMessage() method on the Logger class, I would assume that they are doing different ‘things’. This is contrary to our intentions: In either case, we intend to log an error. Whether we are recording an error with only a message or an entire exception is not relevant. 

In light of these reasons, it would be great if we could overload our LogError() method to take a string errorMessage parameter. And, of course, we can do this:

public void LogError(string errorMessage)
{
   // Log the error message
}

We can now call LogError() as 

logger.LogError(exception);

or as 

logger.LogError("An error has occurred.");

We can call our overloaded version of LogError() with either an exception or an error message.

There are more fascinating things to say on Method Overloading, and I will do so tomorrow.

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply