2CPP11 - Method Overloading

21
METHOD OVERLOADING Michael Heron

description

This is an intermediate conversion course for C++, suitable for second year computing students who may have learned Java or another language in first year.

Transcript of 2CPP11 - Method Overloading

Page 1: 2CPP11 - Method Overloading

METHOD OVERLOADINGMichael Heron

Page 2: 2CPP11 - Method Overloading

Introduction• One of the facilities available in modern programming

languages is that of method overloading.• The ability to have more than one method with the same name in a

particular code space.

• This facility can be use to great effect to permit consistency of an interface across objects.• We’ll talk about that today.

Page 3: 2CPP11 - Method Overloading

Method Overloading• It is not the name of the method which uniquely identifies

a method in C++.• It’s the method signature.• It is the combination of:

• The name of the method• The type and order of parameters.

• This allows us to reuse the same name for a function many times.• We’ve already seen this to a degree with constructor methods.

Page 4: 2CPP11 - Method Overloading

Method Overloading• This allows us to re-use the same method name when

doing so makes logical sense.• We don’t need two method names:

• add_two_ints (int x, int y);• add_two_floats (float x, float y)

• We just need one:• add_two_nums (int x, int y);• add_two_floats (float x, float y);

Page 5: 2CPP11 - Method Overloading

Method Overloading• This allows us to reduce the cognitive burden needed to

use our coded objects.• The fewer methods people have to memorize, the better.

• This comes at a danger:• Overload methods only when it makes sense to do so.

• When the output is the same, just the parameters differ.

• Don’t use it when there are side-effects to choosing particular combinations of parameters.• As far as possible, their execution should be identical.

Page 6: 2CPP11 - Method Overloading

Guidelines for Method Overloading• Like anything in programming, you can do this well or you

can do it badly.• We’re going to aim to do it well.

• There are some guidelines for overloading methods properly.• Use a consistent return type• Ensure consistent parameter names• Ensure consistent parameter orders• Use internal function redirection• Don’t overdo them

Page 7: 2CPP11 - Method Overloading

Use A Consistent Return Type• One of the benefits of method overloading is that it

reduces cognitive burden.• This benefit is lost when overloaded methods have inconsistent

return types.

• As with most guidelines, this is not an iron-cast rule.• Sometimes it makes sense, such as methods that perform

arithmetic.• You don’t want to get an int back when you passed in floats.

Page 8: 2CPP11 - Method Overloading

Ensure Consistent Parameter Names• If you call a parameter ‘name’ in one overloaded method,

don’t call it ‘obName in another’• This is something that is not such an issue for external parties, but

has an impact of ease of maintenance.

• Keep the names of your parameters the same.• Refactor the code to ensure this if necessary.

Page 9: 2CPP11 - Method Overloading

Ensure Consistent Parameter Ordering

• The meaning of parameters should remain consistent across overloaded methods:• void do_stuff (int x, int y, int z);• void do_stuff (int y, int x);

• Mixing and matching the order of parameters is a sure-fire way to increase both cognitive burden and user frustration.• Including your own frustration later!

Page 10: 2CPP11 - Method Overloading

Use Internal Function Redirection• As far as is possible, your overloaded methods should be

public interfaces only.• Internally they should act as ‘wrappers’ around some internal

‘worker’ method.

• The wrappers do only the minimal work required to redirect calls on to the proper method.• Supplying default values for missing info, doing type conversion,

etc.

Page 11: 2CPP11 - Method Overloading

Don’t Overdo It• Combinatorial explosion ensures we can’t provide

implementations for all combinations of all parameters.• Or indeed, that we should attempt it.

• It would be crazy to overload all of the possible combinations of provided and missing info.

• Instead, we provide overloaded methods for those combinations that are most likely to make up the majority of calls.• We can provide a ‘all you can eat’ version too for those with more

specialised requirements.

Page 12: 2CPP11 - Method Overloading

Why Overload Methods?• Provides a consistent interface for your objects.• Reduces cognitive burden on learning new objects.

• Don’t need to learn five methods that do much the same thing.• This is a feature in many older languages.

• Makes code more readable.• Makes code more maintainable.

Page 13: 2CPP11 - Method Overloading

Method Overloading Vs Polymorphism

• Method overloading is often characterised as a kind of polymorphism.• It’s not really polymorphic, but opinions vary.

• It’s closest match is to the idea of ad-hoc polymorphism• The set of possible support options is finite.

• It is a tightly restricted version of parametric polymorphism.• Treating all variables without any reference to a specific type.• C#, Java and C++ all offer facilities to do this.

• But method overloading isn’t it.

Page 14: 2CPP11 - Method Overloading

Method Overloading Vs Polymorphism

• Method overloading can be written in such a way as to make use of polymorphism.• But at its core, it does not adapt to the type of parameters it is

given.

• The choice as to which method to invoke is done at compile time.

• Think of overloading not as a polymorphic facility but as syntactical sleight of hand.

Page 15: 2CPP11 - Method Overloading

Variadic Functions• There are several functions in C and C++ that make use

of variable argument lists.• The printf function in C is probably the best example of this.• As is the format method of Strings in Java.

• In general this is not a good idea…• But it does allow for some functionality that is otherwise awkward

to implement.

• This isn’t quite method overloading…• … but close enough to discuss anyway.

Page 16: 2CPP11 - Method Overloading

Varargs Functionusing namespace std;

int add_nums (int count, ...) { va_list arg; int sum; va_start (arg, count);

for (int i = 0; i < count; i++) { sum += va_arg (arg, int); }

va_end (arg); return sum;}

int main(int argc, char** argv) { cout << add_nums (2, 2, 3) << endl;}

Page 17: 2CPP11 - Method Overloading

Why Use Varargs?• Syntactically nicer to user.

• You don’t need to create arrays when you invoke a function.

• When overloading doesn’t meet our needs.• Overloading does not always play well with varargs.

• Easier to read and understand the code.• No messy collection manipulation.

Page 18: 2CPP11 - Method Overloading

Why Not Use Varargs?• Badly designed functions lead to insecure code.• Type conversions must be handled manually.• Type checking can only be done at runtime in many

cases.• Ideally you want problems to be flagged up by the compiler at

compile-time.

• Doesn’t play nicely with overloading.

Page 19: 2CPP11 - Method Overloading

Varargs in Java• Java 1.5 made available the varargs system for the first

time.• It’s syntatically much easier to do.

• Works in largely the same way.• It’s an autoboxing feature – it creates the array for you.

• Varargs can be used only in the final argument position.

Page 20: 2CPP11 - Method Overloading

Varargs in Javavoid sum_numbers (object ... nums) { int total; Integer num; for (Object o : nums) { num = (Integer)o; total += o.intValue(); } return total;}

Page 21: 2CPP11 - Method Overloading

Summary• Functions have unique signatures that identify them.

• The signature is the name, and then types and order of parameters.

• Overloading functions means that you can produce more readable and more maintainable code.

• Variadic functions can be created to deal with situations where array manipulation would be awkward or costly.