NYCPHP Meetup

NYPHP.org

[nycphp-talk] Method overloading

John Zabroski johnzabroski at yahoo.com
Sun Dec 16 08:42:35 EST 2007


--- Kenneth Downs <ken at secdat.com> wrote:

> Overloading is a requirement for strongly typed
> languages, since PHP is 
> not strongly typed it can get by without it.  I also
> find PHP's loose 
> typing far more appropriate to its role as a string
> generator (sql, 
> HTML), and appreciate its default values as part of
> its entire 
> philosophy of flexibility.

To be quite honest, overloading is rarely ever
necessary even in a language with static types.

The temptation is to use overloading where default
values for parameters are reasonable.  Using
overloading in place of default parameter values leads
to Run-On Initialization bug patterns where part of
the object instantiation code is apart from the
constructor.  This is a code smell, and the only
reason it might have for existing is its legacy code
and "making it right" might actually break it.

If overloading is used for some other reason, then
it's likely still a code smell.  However, instead of
Run-On Initialization, the code smells would be code
duplication and exposing structure.  Typically,
overloading might be used because requirements
changed.  e.g., you thought it was a good idea to use
a formatted string to determine the internal structure
of an object.  This often results in Broken Dispatch
bug patterns.  These aren't usually very obvious when
performing maintenance on code, because typically any
maintenance error only manifests itself in another
class that was depending upon the previously exposed
internal structure.  Yet, for composing objects with
complex graph structures, there are superior
approaches that are more flexible for maintenance. 
One correct approach is to use a Builder pattern and
inject the built structure into the constructor. 
Algorithms should be bound to data structures as late
as possible, and that is another way to say, "program
to an interface, not an implementation".

These nefarious issues with overloading are not at all
obvious, especially the Broken Dispatch, and therefore
a good reason to stay away from overloading whenever
possible.

Ad-hoc polymorphism is more useful, and is sometimes
mistaken for overloading.  Ad-hoc polymorphism is a
way to provide more specific dynamic method dispatch,
helps provide late binding, and thus allows the
execution path to be determined at run-time.


      ____________________________________________________________________________________
Looking for last minute shopping deals?  
Find them fast with Yahoo! Search.  http://tools.search.yahoo.com/newsearch/category.php?category=shopping



More information about the talk mailing list