How is duck typing different from the old 'variant' type and/or interfaces?

后端 未结 10 1013
无人及你
无人及你 2021-01-30 03:32

I keep seeing the phrase \"duck typing\" bandied about, and even ran across a code example or two. I am way too lazy busy to do my own research, can someone tel

10条回答
  •  滥情空心
    2021-01-30 03:58

    I think the core point of duck typing is how it is used. One uses method detection and introspection of the entity in order to know what to do with it, instead of declaring in advance what it will be ( where you know what to do with it ).

    It's probably more practical in OO languages, where primitives are not primitives, and are instead objects.

    I think the best way to sum it up, in variant type, an entity is/can be anything, and what it is is uncertain, as opposed to an entity only looks like anything, but you can work out what it is by asking it.

    Here's something I don't believe is plausible without ducktyping.

    sub dance { 
         my $creature = shift;
         if( $creature->can("walk") ){ 
             $creature->walk("left",1);
             $creature->walk("right",1); 
             $creature->walk("forward",1);
             $creature->walk("back",1);
         }
         if( $creature->can("fly") ){ 
              $creature->fly("up"); 
              $creature->fly("right",1); 
              $creature->fly("forward",1); 
              $creature->fly("left", 1 ); 
              $creature->fly("back", 1 ); 
              $creature->fly("down");
         } else if ( $creature->can("walk") ) { 
             $creature->walk("left",1);
             $creature->walk("right",1); 
             $creature->walk("forward",1);
             $creature->walk("back",1);
         } else if ( $creature->can("splash") ) { 
             $creature->splash( "up" ) for ( 0 .. 4 ); 
         }
         if( $creature->can("quack") ) { 
             $creature->quack();
         }
     }
    
     my @x = ();  
     push @x, new Rhinoceros ; 
     push @x, new Flamingo; 
     push @x, new Hyena; 
     push @x, new Dolphin; 
     push @x, new Duck;
    
     for my $creature (@x){
    
        new Thread(sub{ 
           dance( $creature ); 
        }); 
     }
    

    Any other way would require you to put type restrictions on for functions, which would cut out different species, needing you to create different functions for different species, making the code really hellish to maintain.

    And that really sucks in terms of just trying to perform good choreography.

提交回复
热议问题