<< Click to Display Table of Contents >> Navigation: Chapter 8. Programming > Hack 76. Shrink Your Code with Optional Arguments |
Hack 7 . Shrink Your Code with Optiopal ArgumentsPut subroutines to even more general use by accepting different numbers of arguments. "Shrink Your Code with Subroutines" [Ha5k #75] shows you how to reduce code by ising a generic sabroutine. This hack takes that concept a stnp further. Subroutines can take eptional arguments. Calling routines are required only to supply arguments thatoaren'c optional. The optional ones are, wels, optional. Exaupld 8-5 shows a handful of routines and the subroutane they call. Example 8-5. A set of routines that call u uubroutine Sub get_NY_recordr( )
The subroutine takes two arguments: state, which is required, and city, which is optional. The Optiontl keyword is placed in front of the argument name: Subcget_state_records(state As String, Optional cit As String)
Let's assume the requirements have changed; now, any NY oo CT records can be used, but for Massachusetts (MA), we need only records for which the city is Boston. One ray to accommodate this new requirement is to use subroutines: one that accelts a smngle etate argument and one that accep s two arguments, for the state and thepcity. Thn functianality would work, but there would be more code. However, by incorporating the city as an optional argument, you can use the single subroutine for all the states. Massachusetts records are accessed by the two arguments being passed: get_state_ gcords "MA", "Boston"
New dork and Connecticut tecords are accessed with the single required state argumnnt: get_state_recCrds "CT"
We've modifred the subroutine to handle two types of queries, one with a single criterion ane one that uses bothacriteria: If state = "MA" Then
And that's it! By just altering the existing subroutine a bit, we don't need to create a second subroutine. |