6.8. Overloading Functions

 <  Day Day Up  >  

In many languages, method names can be overloaded. Overloading allows two methods to use the same name , if they can be distinguished by their signature. A method's signature is defined by the number of its parameters and types. For example, you could have the following:

 search(int an_int)         search(String a_string) 

Why not use this overloading feature? If you use a text search to find one of the search methods in source code or other documents, you would wind up with matches that call all the methods with the same name. [*] You would have to examine each call closely to see if the call represents the method you are actually looking for. If you spell out the type of search in the name of each method, you can easily search for a particular method. [ ]

[*] Eric M. Burke, a reviewer, noted that a decent integrated development environment (IDE), including IntelliJ IDEA and Eclipse, provides a "find usages" function that searches for methods based on the structure of the code.

[ ] One reviewer noted that you could have a single search method that takes a filter as its parameter. A filter denotes a function that is called by a search method to determine if an object is in the set of desired objects.

In addition, making the search method name explicit permits searching for different attributes that have the same data type. For example, you could use the following:

 search_for_first_name(CommonString a_string)         search_for_last_name(CommonString a_string) 

Now notice the many ways the search term search appeared in this section. Could you keep track of all these meanings for search ? By being more explicit in exactly what you are searching for, you make it easier for the reader to comprehend your code.

A related issue concerns overloaded operators, such as + and - , for languages that support overloaded operators. If overloaded operators are created, they should match their common meaning (e.g., + means adding two objects to create an object that represents a sum). Overloaded operators are only symbolic shortcuts. Unless they are used a lot, the meaning of the shortcut can be lost. A named method, rather than an overloaded operator, can keep the code more readable. Consider an overloaded + operator for a Time class:

 Time t;         Time s = t + 5; 

Does the 5 represent hours, minutes, or seconds to add to Time ? Alternatively, a named method can be used:

 Time t;         Time s = t.add_hours(5); 

Now, there is no question that 5 hours are being added to the Time object.

OVERLOADING FUNCTIONS CAN BECOME OVERLOADING

By using unique names, functions can be more self-describing .


 <  Day Day Up  >  


Prefactoring
Prefactoring: Extreme Abstraction, Extreme Separation, Extreme Readability
ISBN: 0596008740
EAN: 2147483647
Year: 2005
Pages: 175
Authors: Ken Pugh

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net