/ home / Programming / Python /

Function Overloading

Function overloading allows one to define multiple functions under the same name, taking different arguments. The task below shows the requisite code for overloading:

Python Qt/Cpp
  1. import sys;
  2. class Foo:
  3. x = 1
  4. class Bar:
  5. y = 2
  6. # Start reading here
  7. def debug( T, TT = None ):
  8. if T is Foo and TT is None:
  9. # <FUNCTION DEFINITON>
  10. elif T is Bar and TT is None:
  11. # <FUNCTION DEFINITON>
  12. elif T is Foo and TT is Bar:
  13. # <FUNCTION DEFINITON>
  14. elif T is Bar and TT is Foo:
  15. # <FUNCTION DEFINITON>
  16. else:
  17. sys.exit('Fatal: No Programming')
  1. struct Foo;
  2. struct Bar;
  3. // Start reading here
  4. void debug( const Foo &foo );
  5. void debug( const Bar &bar );
  6. void debug( const Foo &foo, const Bar &bar );
  7. void debug( const Bar &bar, const Foo &foo );

Read as:
  • Define a debug function with two arguments
  • [ whether it returns anything is unknown ]
  • T & TT [ Shorthand for Type ]
  • which implies a generic all purpose argument
  • [ whether this function alters the arguments is unknown ]
  • in which TT equals None [ Undefined ] by default.
  • After several complex conditional statements
  • [ return statements may be hidden in the definitions ]
  • if all else fails then the system exits with the message
  • 'Fatal: No Programming'.
  • Four prototypes of a void type debug function exist
  • [ They are probably defined elsewhere ]
  • whos parameter lists are combinations of
  • [ constant [ read-only ] references to ]
  • Foo and Bar structures.
  • These functions are probably for debugging Foo and Bar.

Benefits:
  • Everything is defined under one function, which some people may like because all the definitions are close together.
  • The syntax ' if T is Foo and TT is None ' is very straight forward and easy to understand.
  • You can be a lot more flexible with the default behaviour, given the dynamic nature of the language.
  • Requisite information [ gleamed from the function signature ] is provided with less lines of code
  • Decoupled, and easy to extend.
  • Logic for determining which definition to use, is handled by compiler.

Drawbacks:
  • Every definition has to exist in an extra indentation.
  • Have to sift through the definitions to read then write your relevant code.
  • The complexity of the conditional statements is relative to the amount of parameters in the function.
  • Its not obvious that this is intended for function overloading, even after glancing at the source code.
  • Bugs are very easy to create in the conditional statements. For example, a person may define some code, but mess up the conditional, and it may never fire when expected.
  • ' TT = None ' is kind of an odd red herring.
  • Difficult to create a dynamic solution using this particular idiom.

Final Thoughts