Diese Präsentation wurde erfolgreich gemeldet.
Wir verwenden Ihre LinkedIn Profilangaben und Informationen zu Ihren Aktivitäten, um Anzeigen zu personalisieren und Ihnen relevantere Inhalte anzuzeigen. Sie können Ihre Anzeigeneinstellungen jederzeit ändern.

2CPP11 - Method Overloading

760 Aufrufe

Veröffentlicht am

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.

Veröffentlicht in: Software, Technologie
  • Als Erste(r) kommentieren

2CPP11 - Method Overloading

  1. 1. METHOD OVERLOADING Michael Heron
  2. 2. 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.
  3. 3. 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.
  4. 4. 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);
  5. 5. 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.
  6. 6. 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
  7. 7. 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.
  8. 8. 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.
  9. 9. 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!
  10. 10. 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.
  11. 11. 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.
  12. 12. 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.
  13. 13. 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.
  14. 14. 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.
  15. 15. 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.
  16. 16. Varargs Function using 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; }
  17. 17. 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.
  18. 18. 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.
  19. 19. 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.
  20. 20. Varargs in Java void sum_numbers (object ... nums) { int total; Integer num; for (Object o : nums) { num = (Integer)o; total += o.intValue(); } return total; }
  21. 21. 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.