SlideShare une entreprise Scribd logo
1  sur  21
METHOD
OVERLOADING
Michael Heron
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.
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.
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);
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.
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
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.
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.
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!
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.
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.
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.
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.
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.
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.
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;
}
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.
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.
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.
Varargs in Java
void sum_numbers (object ... nums) {
int total;
Integer num;
for (Object o : nums) {
num = (Integer)o;
total += o.intValue();
}
return total;
}
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.

Contenu connexe

Tendances (20)

Structural testing
Structural testingStructural testing
Structural testing
 
Introduction to method overloading &amp; method overriding in java hdm
Introduction to method overloading &amp; method overriding  in java  hdmIntroduction to method overloading &amp; method overriding  in java  hdm
Introduction to method overloading &amp; method overriding in java hdm
 
Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in java
 
Method overloading
Method overloadingMethod overloading
Method overloading
 
JVM
JVMJVM
JVM
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
Java Development Kit (jdk)
Java Development Kit (jdk)Java Development Kit (jdk)
Java Development Kit (jdk)
 
Super keyword in java
Super keyword in javaSuper keyword in java
Super keyword in java
 
Method overloading
Method overloadingMethod overloading
Method overloading
 
Designing Techniques in Software Engineering
Designing Techniques in Software EngineeringDesigning Techniques in Software Engineering
Designing Techniques in Software Engineering
 
Ppt on this and super keyword
Ppt on this and super keywordPpt on this and super keyword
Ppt on this and super keyword
 
Wrapper classes
Wrapper classesWrapper classes
Wrapper classes
 
Method Overloading In Java
Method Overloading In JavaMethod Overloading In Java
Method Overloading In Java
 
JAVA AWT
JAVA AWTJAVA AWT
JAVA AWT
 
Features of java
Features of javaFeatures of java
Features of java
 
Introduction to software testing
Introduction to software testingIntroduction to software testing
Introduction to software testing
 
Introduction to Compilers
Introduction to CompilersIntroduction to Compilers
Introduction to Compilers
 
Java(Polymorphism)
Java(Polymorphism)Java(Polymorphism)
Java(Polymorphism)
 
Thread priorities
Thread prioritiesThread priorities
Thread priorities
 
Cost estimation using cocomo model
Cost estimation using cocomo modelCost estimation using cocomo model
Cost estimation using cocomo model
 

En vedette

Socket programming in C#
Socket programming in C#Socket programming in C#
Socket programming in C#Nang Luc Vu
 
Visual Studio Enterprise 2015 Overview atidan
Visual Studio Enterprise 2015 Overview   atidanVisual Studio Enterprise 2015 Overview   atidan
Visual Studio Enterprise 2015 Overview atidanDavid J Rosenthal
 
2CPP08 - Overloading and Overriding
2CPP08 - Overloading and Overriding2CPP08 - Overloading and Overriding
2CPP08 - Overloading and OverridingMichael Heron
 
Polymorphism in java, method overloading and method overriding
Polymorphism in java,  method overloading and method overridingPolymorphism in java,  method overloading and method overriding
Polymorphism in java, method overloading and method overridingJavaTportal
 
c#.Net Windows application
c#.Net Windows application c#.Net Windows application
c#.Net Windows application veera
 
The Psychology of C# Analysis
The Psychology of C# AnalysisThe Psychology of C# Analysis
The Psychology of C# AnalysisCoverity
 
Intro to Xamarin for Visual Studio: Native iOS, Android, and Windows Apps in C#
Intro to Xamarin for Visual Studio: Native iOS, Android, and Windows Apps in C#Intro to Xamarin for Visual Studio: Native iOS, Android, and Windows Apps in C#
Intro to Xamarin for Visual Studio: Native iOS, Android, and Windows Apps in C#Xamarin
 
Microsoft Dynamics NAV 2013 R2 Overview and NAV Roadmap
Microsoft Dynamics NAV 2013 R2 Overview and NAV RoadmapMicrosoft Dynamics NAV 2013 R2 Overview and NAV Roadmap
Microsoft Dynamics NAV 2013 R2 Overview and NAV RoadmapSociusPartner
 
Overloading in java
Overloading in javaOverloading in java
Overloading in java774474
 
encapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloadingencapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloadingShivam Singhal
 

En vedette (20)

Socket programming in C#
Socket programming in C#Socket programming in C#
Socket programming in C#
 
Intro.net
Intro.netIntro.net
Intro.net
 
Visual Studio Enterprise 2015 Overview atidan
Visual Studio Enterprise 2015 Overview   atidanVisual Studio Enterprise 2015 Overview   atidan
Visual Studio Enterprise 2015 Overview atidan
 
2CPP08 - Overloading and Overriding
2CPP08 - Overloading and Overriding2CPP08 - Overloading and Overriding
2CPP08 - Overloading and Overriding
 
Polymorphism in java, method overloading and method overriding
Polymorphism in java,  method overloading and method overridingPolymorphism in java,  method overloading and method overriding
Polymorphism in java, method overloading and method overriding
 
Java Arrays
Java ArraysJava Arrays
Java Arrays
 
c#.Net Windows application
c#.Net Windows application c#.Net Windows application
c#.Net Windows application
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
C# simplified
C#  simplifiedC#  simplified
C# simplified
 
The Psychology of C# Analysis
The Psychology of C# AnalysisThe Psychology of C# Analysis
The Psychology of C# Analysis
 
Intro to Xamarin for Visual Studio: Native iOS, Android, and Windows Apps in C#
Intro to Xamarin for Visual Studio: Native iOS, Android, and Windows Apps in C#Intro to Xamarin for Visual Studio: Native iOS, Android, and Windows Apps in C#
Intro to Xamarin for Visual Studio: Native iOS, Android, and Windows Apps in C#
 
Windowforms controls c#
Windowforms controls c#Windowforms controls c#
Windowforms controls c#
 
Microsoft Dynamics NAV 2013 R2 Overview and NAV Roadmap
Microsoft Dynamics NAV 2013 R2 Overview and NAV RoadmapMicrosoft Dynamics NAV 2013 R2 Overview and NAV Roadmap
Microsoft Dynamics NAV 2013 R2 Overview and NAV Roadmap
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Method overloading
Method overloadingMethod overloading
Method overloading
 
Overloading in java
Overloading in javaOverloading in java
Overloading in java
 
encapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloadingencapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloading
 
Method overloading and constructor overloading in java
Method overloading and constructor overloading in javaMethod overloading and constructor overloading in java
Method overloading and constructor overloading in java
 
Arrays in java
Arrays in javaArrays in java
Arrays in java
 

Similaire à 2CPP11 - Method Overloading

2CPP12 - Method Overriding
2CPP12 - Method Overriding2CPP12 - Method Overriding
2CPP12 - Method OverridingMichael Heron
 
Working With Concurrency In Java 8
Working With Concurrency In Java 8Working With Concurrency In Java 8
Working With Concurrency In Java 8Heartin Jacob
 
Principled And Clean Coding
Principled And Clean CodingPrincipled And Clean Coding
Principled And Clean CodingMetin Ogurlu
 
overloading
overloadingoverloading
overloadingcpsivaku
 
Design Like a Pro: Scripting Best Practices
Design Like a Pro: Scripting Best PracticesDesign Like a Pro: Scripting Best Practices
Design Like a Pro: Scripting Best PracticesInductive Automation
 
Reading Notes : the practice of programming
Reading Notes : the practice of programmingReading Notes : the practice of programming
Reading Notes : the practice of programmingJuggernaut Liu
 
Design Like a Pro: Scripting Best Practices
Design Like a Pro: Scripting Best PracticesDesign Like a Pro: Scripting Best Practices
Design Like a Pro: Scripting Best PracticesInductive Automation
 
classVII_Coding_Teacher_Presentation.pptx
classVII_Coding_Teacher_Presentation.pptxclassVII_Coding_Teacher_Presentation.pptx
classVII_Coding_Teacher_Presentation.pptxssusere336f4
 
Introduction to c first week slides
Introduction to c first week slidesIntroduction to c first week slides
Introduction to c first week slidesluqman bawany
 
Refactoring: Improving the design of existing code. Chapter 6.
Refactoring: Improving the design of existing code. Chapter 6.Refactoring: Improving the design of existing code. Chapter 6.
Refactoring: Improving the design of existing code. Chapter 6.Andrés Callejas González
 
What To Leave Implicit
What To Leave ImplicitWhat To Leave Implicit
What To Leave ImplicitMartin Odersky
 
2CPP04 - Objects and Classes
2CPP04 - Objects and Classes2CPP04 - Objects and Classes
2CPP04 - Objects and ClassesMichael Heron
 
Complete PPT about the Java lokesh kept it
Complete PPT about the Java lokesh kept itComplete PPT about the Java lokesh kept it
Complete PPT about the Java lokesh kept itlokeshpappaka10
 

Similaire à 2CPP11 - Method Overloading (20)

CPP03 - Repetition
CPP03 - RepetitionCPP03 - Repetition
CPP03 - Repetition
 
2CPP19 - Summation
2CPP19 - Summation2CPP19 - Summation
2CPP19 - Summation
 
CPP19 - Revision
CPP19 - RevisionCPP19 - Revision
CPP19 - Revision
 
DAA Unit 1.pdf
DAA Unit 1.pdfDAA Unit 1.pdf
DAA Unit 1.pdf
 
2CPP12 - Method Overriding
2CPP12 - Method Overriding2CPP12 - Method Overriding
2CPP12 - Method Overriding
 
Working With Concurrency In Java 8
Working With Concurrency In Java 8Working With Concurrency In Java 8
Working With Concurrency In Java 8
 
Principled And Clean Coding
Principled And Clean CodingPrincipled And Clean Coding
Principled And Clean Coding
 
overloading
overloadingoverloading
overloading
 
Design Like a Pro: Scripting Best Practices
Design Like a Pro: Scripting Best PracticesDesign Like a Pro: Scripting Best Practices
Design Like a Pro: Scripting Best Practices
 
Reading Notes : the practice of programming
Reading Notes : the practice of programmingReading Notes : the practice of programming
Reading Notes : the practice of programming
 
Design Like a Pro: Scripting Best Practices
Design Like a Pro: Scripting Best PracticesDesign Like a Pro: Scripting Best Practices
Design Like a Pro: Scripting Best Practices
 
Design p atterns
Design p atternsDesign p atterns
Design p atterns
 
classVII_Coding_Teacher_Presentation.pptx
classVII_Coding_Teacher_Presentation.pptxclassVII_Coding_Teacher_Presentation.pptx
classVII_Coding_Teacher_Presentation.pptx
 
12.6-12.9.pptx
12.6-12.9.pptx12.6-12.9.pptx
12.6-12.9.pptx
 
Introduction to c first week slides
Introduction to c first week slidesIntroduction to c first week slides
Introduction to c first week slides
 
Clean code
Clean codeClean code
Clean code
 
Refactoring: Improving the design of existing code. Chapter 6.
Refactoring: Improving the design of existing code. Chapter 6.Refactoring: Improving the design of existing code. Chapter 6.
Refactoring: Improving the design of existing code. Chapter 6.
 
What To Leave Implicit
What To Leave ImplicitWhat To Leave Implicit
What To Leave Implicit
 
2CPP04 - Objects and Classes
2CPP04 - Objects and Classes2CPP04 - Objects and Classes
2CPP04 - Objects and Classes
 
Complete PPT about the Java lokesh kept it
Complete PPT about the Java lokesh kept itComplete PPT about the Java lokesh kept it
Complete PPT about the Java lokesh kept it
 

Plus de Michael Heron

Meeple centred design - Board Game Accessibility
Meeple centred design - Board Game AccessibilityMeeple centred design - Board Game Accessibility
Meeple centred design - Board Game AccessibilityMichael Heron
 
Musings on misconduct
Musings on misconductMusings on misconduct
Musings on misconductMichael Heron
 
Accessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS FrameworkAccessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS FrameworkMichael Heron
 
ACCESS: A Technical Framework for Adaptive Accessibility Support
ACCESS:  A Technical Framework for Adaptive Accessibility SupportACCESS:  A Technical Framework for Adaptive Accessibility Support
ACCESS: A Technical Framework for Adaptive Accessibility SupportMichael Heron
 
Authorship and Autership
Authorship and AutershipAuthorship and Autership
Authorship and AutershipMichael Heron
 
Text parser based interaction
Text parser based interactionText parser based interaction
Text parser based interactionMichael Heron
 
GRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and RadiosityGRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and RadiosityMichael Heron
 
GRPHICS07 - Textures
GRPHICS07 - TexturesGRPHICS07 - Textures
GRPHICS07 - TexturesMichael Heron
 
GRPHICS05 - Rendering (2)
GRPHICS05 - Rendering (2)GRPHICS05 - Rendering (2)
GRPHICS05 - Rendering (2)Michael Heron
 
GRPHICS04 - Rendering (1)
GRPHICS04 - Rendering (1)GRPHICS04 - Rendering (1)
GRPHICS04 - Rendering (1)Michael Heron
 
GRPHICS03 - Graphical Representation
GRPHICS03 - Graphical RepresentationGRPHICS03 - Graphical Representation
GRPHICS03 - Graphical RepresentationMichael Heron
 
GRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D GraphicsGRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D GraphicsMichael Heron
 
GRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D GraphicsGRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D GraphicsMichael Heron
 
GRPHICS09 - Art Appreciation
GRPHICS09 - Art AppreciationGRPHICS09 - Art Appreciation
GRPHICS09 - Art AppreciationMichael Heron
 

Plus de Michael Heron (20)

Meeple centred design - Board Game Accessibility
Meeple centred design - Board Game AccessibilityMeeple centred design - Board Game Accessibility
Meeple centred design - Board Game Accessibility
 
Musings on misconduct
Musings on misconductMusings on misconduct
Musings on misconduct
 
Accessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS FrameworkAccessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS Framework
 
ACCESS: A Technical Framework for Adaptive Accessibility Support
ACCESS:  A Technical Framework for Adaptive Accessibility SupportACCESS:  A Technical Framework for Adaptive Accessibility Support
ACCESS: A Technical Framework for Adaptive Accessibility Support
 
Authorship and Autership
Authorship and AutershipAuthorship and Autership
Authorship and Autership
 
Text parser based interaction
Text parser based interactionText parser based interaction
Text parser based interaction
 
SAD04 - Inheritance
SAD04 - InheritanceSAD04 - Inheritance
SAD04 - Inheritance
 
GRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and RadiosityGRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and Radiosity
 
GRPHICS07 - Textures
GRPHICS07 - TexturesGRPHICS07 - Textures
GRPHICS07 - Textures
 
GRPHICS06 - Shading
GRPHICS06 - ShadingGRPHICS06 - Shading
GRPHICS06 - Shading
 
GRPHICS05 - Rendering (2)
GRPHICS05 - Rendering (2)GRPHICS05 - Rendering (2)
GRPHICS05 - Rendering (2)
 
GRPHICS04 - Rendering (1)
GRPHICS04 - Rendering (1)GRPHICS04 - Rendering (1)
GRPHICS04 - Rendering (1)
 
GRPHICS03 - Graphical Representation
GRPHICS03 - Graphical RepresentationGRPHICS03 - Graphical Representation
GRPHICS03 - Graphical Representation
 
GRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D GraphicsGRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D Graphics
 
GRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D GraphicsGRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D Graphics
 
GRPHICS09 - Art Appreciation
GRPHICS09 - Art AppreciationGRPHICS09 - Art Appreciation
GRPHICS09 - Art Appreciation
 
2CPP18 - Modifiers
2CPP18 - Modifiers2CPP18 - Modifiers
2CPP18 - Modifiers
 
2CPP17 - File IO
2CPP17 - File IO2CPP17 - File IO
2CPP17 - File IO
 
2CPP16 - STL
2CPP16 - STL2CPP16 - STL
2CPP16 - STL
 
2CPP15 - Templates
2CPP15 - Templates2CPP15 - Templates
2CPP15 - Templates
 

Dernier

Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....ShaimaaMohamedGalal
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 

Dernier (20)

Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 

2CPP11 - Method Overloading

  • 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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.