Empty list as default parameter

Jay O'Connor joconnor at nets.com
Sun Nov 23 00:46:58 EST 2003


Bengt Richter wrote:

>On 22 Nov 2003 19:05:58 -0800, Paul Rubin <http://phr.cx@NOSPAM.invalid> wrote:
>
>  
>
>>bokr at oz.net (Bengt Richter) writes:
>>    
>>
>>>Yes. The bindings of default values for call args are evaluated at
>>>define-time, in the context of the definition, not at execution
>>>time, when the function is called.
>>>      
>>>
>>That's always seemed like a source of bugs to me, and ugly workarounds
>>for the bugs.  Is there any corresponding disadvantage to eval'ing the
>>defaults at runtime as is done in other languages?
>>    
>>
>What languages are you thinking of? A concrete example for comparison would
>clarify things. 
>

One example that had not occurred to me until reading this thread has to 
do with how Smalltalk methods are built.  Since Smalltalk doesn't allow 
for default parameters, one very common idiom is for a developer to 
create a sort of 'cascade' effect of multiple methods.  The full method 
will require all the paremeters,but one or more of the more common ways 
of using the method will be provided which just turn around and call the 
main method with some default parameter provided for the paramaters not 
beiing specified.

An example:

    Canvas>>drawShape: aShape color: aColor pen: aPen

        "do all the drawing in this method."
       ...

Now, if the developer decides that often the color or pen are going to 
be pretty standard he may provide some 'convenience methods' that other 
developers can call that in turn  just call the main method with defaults.

    Canvas>>drawShape: aShape

        "Use default color of balck and a solid pen"
        ^self drawShape: aShape color: #black pen: #solid

    Canvas>>drawShape: aShape color: aColor

        ^self drawShape: aShape color: aColor pen: #solid

    Canvas>>drawShape: aShape pen: aPen

        ^self drawShape: aShape: color: #black pen: aPen.

This can be a built akward to write sometimes, but makes life pretty 
nice for the other developers.  This is not alwasy the case but just 
based on what the developer thinks are going to be likely patterns of use.

What came to mind, of course, is that this allows the defaults to be 
dynamic.

    Canvas>>drawShape: aShape
       ^self drawShape: aShape color: self currentColor pen: self currentPen

You are still providing defaults, but the defaults are based on the 
current state of the system at execution, not at compile time.  This is 
actually a fairly common idiom in Smalltalk, but Smalltalk's mechanism 
for method signatures is fairly unique and happens to support this 
approach well.






More information about the Python-list mailing list