SlideShare une entreprise Scribd logo
1  sur  20
Télécharger pour lire hors ligne
Object::Trampoline

 When having not the object you want 
         is what you need.




          Steven Lembark
      <lembark@wrkhors.com>
Er... what's “trampoline” object?
●
    Trampolines not the object you want.
●
    They are a proxy for the constructor of another 
    object – the one you want.
●
    Their behavior is replacing themselves when you 
    call a method on them.
●
    Aside from calling a separate constructor, the user 
    shouldn't know the trampoline ever existed.
Why bother?
●
    When you don't want an object until you need it:
    –   Connections to servers that not always used/available 
        (e.g., during development or unit testing).
    –   Avoid construcing expensive, seldom­used objects.
    –    Delay connections to back­end servers until necessary.
●
    Think of starting up a heavily­forked apache server 
    and not bringing your database to its knees.
●
    Or not parsing really large XML until you use it.
WARNING:

The code you are about to see 
  contains graphic AUTOLOAD, 
  literal blessing, and re­
assignment of stack variables.



 Parenthetical discresion is 
          advised.
How do you bounce an object?
●
    Easily, in Perl (pity the poor slobs using Java!).
    –   Perl's AUTOLOAD mechanism allows you to intercept 
        method calls cleanly.
    –   Passing arguments by reference allows replacing them on 
        the stack: assigning to $_[0] gives your caller a new 
        object on the fly.
    –   “goto &sub” replaces one call with another.
●
    Result:  a re­dispatched call with a new object.
Co­Operating Classes
●
    The Object::Trampoline (“O::T”) module uses two 
    classes: a constructor and dispatcher.
●
    O::T itself is nothing but an AUTOLOAD.
●
    It returns a closure blessed into 
    Object::Trampoline::Bounce (“O::T::B”).
●
    O::T::B is nothing but (surprise!) an AUTOLOAD. 
●
    O::T::B replaces the object, re­dispatches the call.
Replacing an Object
●
    O::T::B::AUTOLOAD begins by replacing the stack 
    argument with the result of running itself:
          $_[0] = $_[0]­>();

    ●
        This replaces the caller's copy of the object with a 
        delayed call to the constructor.
    ●
        This new object is then used to locate the 
        requested subroutine via “can”.
Using Object::Trampoline
●
    The difference you'll see in using a trampoline 
    object is in the constructor.
●
    The 'real' class becomes the first argument, and 
    “Object::Trampoline” becomes the new class:

my $dbh = DBI­>connect( $dsn,@argz);

becomes:

my $dbh = Object::Tram poline ‑>connect
( 'DBI', $dsn, @argz );
Under the hood
 ●
     O::T's AUTOLOAD handles the construction by 
     blessing a closure that does the real work:
my ( undef, $class, @argz ) = @_;


my $meth = ( split $AUTOLOAD, '::' )[­1];


my $sub  = sub { $class­>$meth( @argz ) };


bless $sub, 'Object::Trampoline::Bounce'
Using the object
 ●
     At this point the caller gets back what looks like an 
     ordinary object:
# $dbh starts out as a trampoline


my $dbh = 
Object::Trampoline‑>connect( 'DBI', ... );


# the method call converts it to a DBI object.


my $sth = $dbh­>prepare( ... );


# from this point on there's no way to tell 
# that $dbh wasn't a DBI object all along.
Converting the Object
●
    The assignment to $_[0] is made in 
    O::T::B::AUTOLOAD.
●
    If $_[0]­>can( $method ) then it uses goto, 
    otherwise it has to try $_[0]­>$method( @argz ) and 
    hope for the best (e.g., another AUTOLOAD).
●
    It also has contains a stub DESTROY to avoid 
    constructing objects when the go out of scope.
Object::Trampoline::Bounce
our $AUTOLOAD = '';
AUTOLOAD
{
    $_[0] = $_[0]­>();
    my $class  = ref $_[0];
    my $method = ( split /::/, $AUTOLOAD )[ ­1 ];
    if( my $sub = $_[0]­>can( $method ) )
    {
        goto &$sub
    }
    else
    {
        my $obj = shift;
        $obj­>$method( @_ )
    }
}


DESTROY {}
But wait, there's more!
●
    What if requiring the module is the expensive part?
●
    You want to delay the “use” until necessary, not just 
    the construction?
●
    Object::Trampoline::Use does exactly that:
    my sub
    = sub
    {
        eval “package $caller; use $class;


        $class­>$method( @argz )
    };
Why use a closure?
●
    I could have stored the arguments in a hash, with 
    $object­>{ class } and $object­>{ arguments }.
●
    But then there would be a difference in handling 
    different objects that came from O::T or O::T::U.
●
    The closure allows each handler class to handle the 
    construction its own way without to specialize 
    O::T::B for each of them.
Example: Server Handles
●
    Centralizing the data for your server handles can be 
    helpful.
●
    All of the mess for describing DBI, Syslog, HTTP, 
    SOAP... connections can be pushed into one place.
●
    Catch: Not all of the servers are always available, or 
    necessary.
●
    Fix: Export trampolines.
Server::Handles
package Server::Handle;
use Server::Configure
qw
(
     dbi_user ...
     syslog_server ...
);
my %handlerz =
(
     dbh     =>
     Object::Trampoline‑>connect( 'DBI', ... ),


     syslogh =>
     Object::Trampoline‑>openlog( 'Syslog::Wrapper', ... ),
);
sub import
{
   # push the handlers out as­is via *$glob = $value.
   # the values are shared and the first place they are
   # used bounces them for the entire process
}
Trampoline as a Factory
●
    This cannot be avoided, therefore it is a feature.
●
    Unwrapping the stack into a lexical before calling a 
    method on the trampoline updates the lexical, not 
    the caller's copy.
    $foo­>my_wrapper;


    sub my_wrapper
    {
        my $obj    = shift; # my_wrapper copy of $foo


        $obj­>some_method;  # updates $obj, not $foo
Caveat Utilitor
●
    Trampoline objects can only dispatch methods.
●
    If your object is tied then it'll blow up if you try to 
    access its tied interface:
    –   $dbh­>{ AutoCommit } = 0; # dies here for trampoline
●
    None of the ways around this are transparent to the 
    user, but even with DBI the simple fix is to use 
    methods to configure the object.
“ref” is not a method
●
    Until a method is called, “ref $object” will give you 
    “Object::Trampoline::Bounce” and “reftype” will 
    give you back “CODE”.
●
    This mainly affects the use of inside­out data, since 
    $object_data{ refaddr $object } will change after the 
    first method call.
Prototypes are Evil.
●
    Notice the closure:                                                       
             $class­>$constructor( @argz )
●
    Defining $constructor with a prototype of ($$) will 
    break even if you have two values in @argz!
●
    <soapbox>                                                               
    Add code or use Class::Contract (whatever) to 
    actually validate the arguments. Breaking Perl's 
    calling convention only causes pain.         
    </soapbox>.

Contenu connexe

Tendances

GDayX - Advanced Angular.JS
GDayX - Advanced Angular.JSGDayX - Advanced Angular.JS
GDayX - Advanced Angular.JSNicolas Embleton
 
Introduction to Prototype JS Framework
Introduction to Prototype JS FrameworkIntroduction to Prototype JS Framework
Introduction to Prototype JS FrameworkMohd Imran
 
AngularJS with TypeScript and Windows Azure Mobile Services
AngularJS with TypeScript and Windows Azure Mobile ServicesAngularJS with TypeScript and Windows Azure Mobile Services
AngularJS with TypeScript and Windows Azure Mobile ServicesRainer Stropek
 
Intro to Angular.JS Directives
Intro to Angular.JS DirectivesIntro to Angular.JS Directives
Intro to Angular.JS DirectivesChristian Lilley
 
Ten useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesTen useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesAnkit Rastogi
 
Crafting Quality PHP Applications (PHP Benelux 2018)
Crafting Quality PHP Applications (PHP Benelux 2018)Crafting Quality PHP Applications (PHP Benelux 2018)
Crafting Quality PHP Applications (PHP Benelux 2018)James Titcumb
 
Writing JavaScript that doesn't suck
Writing JavaScript that doesn't suckWriting JavaScript that doesn't suck
Writing JavaScript that doesn't suckRoss Bruniges
 
Dip Your Toes in the Sea of Security (ConFoo YVR 2017)
Dip Your Toes in the Sea of Security (ConFoo YVR 2017)Dip Your Toes in the Sea of Security (ConFoo YVR 2017)
Dip Your Toes in the Sea of Security (ConFoo YVR 2017)James Titcumb
 
Advanced javascript
Advanced javascriptAdvanced javascript
Advanced javascriptDoeun KOCH
 
AngularJs $provide API internals & circular dependency problem.
AngularJs $provide API internals & circular dependency problem.AngularJs $provide API internals & circular dependency problem.
AngularJs $provide API internals & circular dependency problem.Yan Yankowski
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5arajivmordani
 
Crafting Quality PHP Applications (Bucharest Tech Week 2017)
Crafting Quality PHP Applications (Bucharest Tech Week 2017)Crafting Quality PHP Applications (Bucharest Tech Week 2017)
Crafting Quality PHP Applications (Bucharest Tech Week 2017)James Titcumb
 
Testing ASP.net Web Applications using Ruby
Testing ASP.net Web Applications using RubyTesting ASP.net Web Applications using Ruby
Testing ASP.net Web Applications using RubyBen Hall
 
Crafting Quality PHP Applications (ConFoo YVR 2017)
Crafting Quality PHP Applications (ConFoo YVR 2017)Crafting Quality PHP Applications (ConFoo YVR 2017)
Crafting Quality PHP Applications (ConFoo YVR 2017)James Titcumb
 
AngularJS Architecture
AngularJS ArchitectureAngularJS Architecture
AngularJS ArchitectureEyal Vardi
 
JavaScript APIs you’ve never heard of (and some you have)
JavaScript APIs you’ve never heard of (and some you have)JavaScript APIs you’ve never heard of (and some you have)
JavaScript APIs you’ve never heard of (and some you have)Nicholas Zakas
 
Workshop 8: Templating: Handlebars, DustJS
Workshop 8: Templating: Handlebars, DustJSWorkshop 8: Templating: Handlebars, DustJS
Workshop 8: Templating: Handlebars, DustJSVisual Engineering
 

Tendances (20)

GDayX - Advanced Angular.JS
GDayX - Advanced Angular.JSGDayX - Advanced Angular.JS
GDayX - Advanced Angular.JS
 
Introduction to Prototype JS Framework
Introduction to Prototype JS FrameworkIntroduction to Prototype JS Framework
Introduction to Prototype JS Framework
 
AngularJS with TypeScript and Windows Azure Mobile Services
AngularJS with TypeScript and Windows Azure Mobile ServicesAngularJS with TypeScript and Windows Azure Mobile Services
AngularJS with TypeScript and Windows Azure Mobile Services
 
Intro to Angular.JS Directives
Intro to Angular.JS DirectivesIntro to Angular.JS Directives
Intro to Angular.JS Directives
 
JavaScript Neednt Hurt - JavaBin talk
JavaScript Neednt Hurt - JavaBin talkJavaScript Neednt Hurt - JavaBin talk
JavaScript Neednt Hurt - JavaBin talk
 
Ten useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesTen useful JavaScript tips & best practices
Ten useful JavaScript tips & best practices
 
Crafting Quality PHP Applications (PHP Benelux 2018)
Crafting Quality PHP Applications (PHP Benelux 2018)Crafting Quality PHP Applications (PHP Benelux 2018)
Crafting Quality PHP Applications (PHP Benelux 2018)
 
The Beauty of Java Script
The Beauty of Java ScriptThe Beauty of Java Script
The Beauty of Java Script
 
Writing JavaScript that doesn't suck
Writing JavaScript that doesn't suckWriting JavaScript that doesn't suck
Writing JavaScript that doesn't suck
 
Dip Your Toes in the Sea of Security (ConFoo YVR 2017)
Dip Your Toes in the Sea of Security (ConFoo YVR 2017)Dip Your Toes in the Sea of Security (ConFoo YVR 2017)
Dip Your Toes in the Sea of Security (ConFoo YVR 2017)
 
Advanced javascript
Advanced javascriptAdvanced javascript
Advanced javascript
 
jQuery PPT
jQuery PPTjQuery PPT
jQuery PPT
 
AngularJs $provide API internals & circular dependency problem.
AngularJs $provide API internals & circular dependency problem.AngularJs $provide API internals & circular dependency problem.
AngularJs $provide API internals & circular dependency problem.
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5a
 
Crafting Quality PHP Applications (Bucharest Tech Week 2017)
Crafting Quality PHP Applications (Bucharest Tech Week 2017)Crafting Quality PHP Applications (Bucharest Tech Week 2017)
Crafting Quality PHP Applications (Bucharest Tech Week 2017)
 
Testing ASP.net Web Applications using Ruby
Testing ASP.net Web Applications using RubyTesting ASP.net Web Applications using Ruby
Testing ASP.net Web Applications using Ruby
 
Crafting Quality PHP Applications (ConFoo YVR 2017)
Crafting Quality PHP Applications (ConFoo YVR 2017)Crafting Quality PHP Applications (ConFoo YVR 2017)
Crafting Quality PHP Applications (ConFoo YVR 2017)
 
AngularJS Architecture
AngularJS ArchitectureAngularJS Architecture
AngularJS Architecture
 
JavaScript APIs you’ve never heard of (and some you have)
JavaScript APIs you’ve never heard of (and some you have)JavaScript APIs you’ve never heard of (and some you have)
JavaScript APIs you’ve never heard of (and some you have)
 
Workshop 8: Templating: Handlebars, DustJS
Workshop 8: Templating: Handlebars, DustJSWorkshop 8: Templating: Handlebars, DustJS
Workshop 8: Templating: Handlebars, DustJS
 

Similaire à Object Trampoline

Professional JavaScript Development - Creating Reusable Code
Professional JavaScript Development -  Creating Reusable CodeProfessional JavaScript Development -  Creating Reusable Code
Professional JavaScript Development - Creating Reusable CodeWildan Maulana
 
Object Trampoline: Why having not the object you want is what you need.
Object Trampoline: Why having not the object you want is what you need.Object Trampoline: Why having not the object you want is what you need.
Object Trampoline: Why having not the object you want is what you need.Workhorse Computing
 
Object Oriented Programming for WordPress Plugin Development
Object Oriented Programming for WordPress Plugin DevelopmentObject Oriented Programming for WordPress Plugin Development
Object Oriented Programming for WordPress Plugin Developmentmtoppa
 
Object-Oriented JavaScript
Object-Oriented JavaScriptObject-Oriented JavaScript
Object-Oriented JavaScriptWildan Maulana
 
Turbogears Presentation
Turbogears PresentationTurbogears Presentation
Turbogears Presentationdidip
 
Functional FIPS: Learning PHP for Drupal Theming
Functional FIPS: Learning PHP for Drupal ThemingFunctional FIPS: Learning PHP for Drupal Theming
Functional FIPS: Learning PHP for Drupal ThemingEmma Jane Hogbin Westby
 
Beijing Perl Workshop 2008 Hiveminder Secret Sauce
Beijing Perl Workshop 2008 Hiveminder Secret SauceBeijing Perl Workshop 2008 Hiveminder Secret Sauce
Beijing Perl Workshop 2008 Hiveminder Secret SauceJesse Vincent
 
Dependency Inversion and Dependency Injection in PHP
Dependency Inversion and Dependency Injection in PHPDependency Inversion and Dependency Injection in PHP
Dependency Inversion and Dependency Injection in PHPmtoppa
 
FRONT-END COMPONENTS IN DRUPAL THEME. "KAIZEN" - DRUPAL 8 THEME FROM SKILLD
FRONT-END COMPONENTS IN DRUPAL THEME. "KAIZEN" - DRUPAL 8 THEME FROM SKILLDFRONT-END COMPONENTS IN DRUPAL THEME. "KAIZEN" - DRUPAL 8 THEME FROM SKILLD
FRONT-END COMPONENTS IN DRUPAL THEME. "KAIZEN" - DRUPAL 8 THEME FROM SKILLDDrupalCamp Kyiv
 
Drupal Development
Drupal DevelopmentDrupal Development
Drupal DevelopmentJeff Eaton
 
Object::Franger: Wear a Raincoat in your Code
Object::Franger: Wear a Raincoat in your CodeObject::Franger: Wear a Raincoat in your Code
Object::Franger: Wear a Raincoat in your CodeWorkhorse Computing
 
Debugging in drupal 8
Debugging in drupal 8Debugging in drupal 8
Debugging in drupal 8Allie Jones
 
Choosing a Javascript Framework
Choosing a Javascript FrameworkChoosing a Javascript Framework
Choosing a Javascript FrameworkAll Things Open
 

Similaire à Object Trampoline (20)

Professional JavaScript Development - Creating Reusable Code
Professional JavaScript Development -  Creating Reusable CodeProfessional JavaScript Development -  Creating Reusable Code
Professional JavaScript Development - Creating Reusable Code
 
Object Trampoline: Why having not the object you want is what you need.
Object Trampoline: Why having not the object you want is what you need.Object Trampoline: Why having not the object you want is what you need.
Object Trampoline: Why having not the object you want is what you need.
 
Object Exercise
Object ExerciseObject Exercise
Object Exercise
 
Object Oriented Programming for WordPress Plugin Development
Object Oriented Programming for WordPress Plugin DevelopmentObject Oriented Programming for WordPress Plugin Development
Object Oriented Programming for WordPress Plugin Development
 
Object-Oriented JavaScript
Object-Oriented JavaScriptObject-Oriented JavaScript
Object-Oriented JavaScript
 
Turbogears Presentation
Turbogears PresentationTurbogears Presentation
Turbogears Presentation
 
mro-every.pdf
mro-every.pdfmro-every.pdf
mro-every.pdf
 
Lazy Data Using Perl
Lazy Data Using PerlLazy Data Using Perl
Lazy Data Using Perl
 
syn
synsyn
syn
 
Functional FIPS: Learning PHP for Drupal Theming
Functional FIPS: Learning PHP for Drupal ThemingFunctional FIPS: Learning PHP for Drupal Theming
Functional FIPS: Learning PHP for Drupal Theming
 
Beijing Perl Workshop 2008 Hiveminder Secret Sauce
Beijing Perl Workshop 2008 Hiveminder Secret SauceBeijing Perl Workshop 2008 Hiveminder Secret Sauce
Beijing Perl Workshop 2008 Hiveminder Secret Sauce
 
Dependency Inversion and Dependency Injection in PHP
Dependency Inversion and Dependency Injection in PHPDependency Inversion and Dependency Injection in PHP
Dependency Inversion and Dependency Injection in PHP
 
FRONT-END COMPONENTS IN DRUPAL THEME. "KAIZEN" - DRUPAL 8 THEME FROM SKILLD
FRONT-END COMPONENTS IN DRUPAL THEME. "KAIZEN" - DRUPAL 8 THEME FROM SKILLDFRONT-END COMPONENTS IN DRUPAL THEME. "KAIZEN" - DRUPAL 8 THEME FROM SKILLD
FRONT-END COMPONENTS IN DRUPAL THEME. "KAIZEN" - DRUPAL 8 THEME FROM SKILLD
 
Drupal Development
Drupal DevelopmentDrupal Development
Drupal Development
 
Advanced Silverlight
Advanced SilverlightAdvanced Silverlight
Advanced Silverlight
 
Java Script Best Practices
Java Script Best PracticesJava Script Best Practices
Java Script Best Practices
 
Object::Franger: Wear a Raincoat in your Code
Object::Franger: Wear a Raincoat in your CodeObject::Franger: Wear a Raincoat in your Code
Object::Franger: Wear a Raincoat in your Code
 
Debugging in drupal 8
Debugging in drupal 8Debugging in drupal 8
Debugging in drupal 8
 
Qpsmtpd
QpsmtpdQpsmtpd
Qpsmtpd
 
Choosing a Javascript Framework
Choosing a Javascript FrameworkChoosing a Javascript Framework
Choosing a Javascript Framework
 

Plus de Workhorse Computing

Wheels we didn't re-invent: Perl's Utility Modules
Wheels we didn't re-invent: Perl's Utility ModulesWheels we didn't re-invent: Perl's Utility Modules
Wheels we didn't re-invent: Perl's Utility ModulesWorkhorse Computing
 
Paranormal statistics: Counting What Doesn't Add Up
Paranormal statistics: Counting What Doesn't Add UpParanormal statistics: Counting What Doesn't Add Up
Paranormal statistics: Counting What Doesn't Add UpWorkhorse Computing
 
The $path to knowledge: What little it take to unit-test Perl.
The $path to knowledge: What little it take to unit-test Perl.The $path to knowledge: What little it take to unit-test Perl.
The $path to knowledge: What little it take to unit-test Perl.Workhorse Computing
 
Generating & Querying Calendar Tables in Posgresql
Generating & Querying Calendar Tables in PosgresqlGenerating & Querying Calendar Tables in Posgresql
Generating & Querying Calendar Tables in PosgresqlWorkhorse Computing
 
Hypers and Gathers and Takes! Oh my!
Hypers and Gathers and Takes! Oh my!Hypers and Gathers and Takes! Oh my!
Hypers and Gathers and Takes! Oh my!Workhorse Computing
 
BSDM with BASH: Command Interpolation
BSDM with BASH: Command InterpolationBSDM with BASH: Command Interpolation
BSDM with BASH: Command InterpolationWorkhorse Computing
 
BASH Variables Part 1: Basic Interpolation
BASH Variables Part 1: Basic InterpolationBASH Variables Part 1: Basic Interpolation
BASH Variables Part 1: Basic InterpolationWorkhorse Computing
 
The W-curve and its application.
The W-curve and its application.The W-curve and its application.
The W-curve and its application.Workhorse Computing
 
Keeping objects healthy with Object::Exercise.
Keeping objects healthy with Object::Exercise.Keeping objects healthy with Object::Exercise.
Keeping objects healthy with Object::Exercise.Workhorse Computing
 
Perl6 Regexen: Reduce the line noise in your code.
Perl6 Regexen: Reduce the line noise in your code.Perl6 Regexen: Reduce the line noise in your code.
Perl6 Regexen: Reduce the line noise in your code.Workhorse Computing
 
Neatly Hashing a Tree: FP tree-fold in Perl5 & Perl6
Neatly Hashing a Tree: FP tree-fold in Perl5 & Perl6Neatly Hashing a Tree: FP tree-fold in Perl5 & Perl6
Neatly Hashing a Tree: FP tree-fold in Perl5 & Perl6Workhorse Computing
 

Plus de Workhorse Computing (20)

Wheels we didn't re-invent: Perl's Utility Modules
Wheels we didn't re-invent: Perl's Utility ModulesWheels we didn't re-invent: Perl's Utility Modules
Wheels we didn't re-invent: Perl's Utility Modules
 
Paranormal statistics: Counting What Doesn't Add Up
Paranormal statistics: Counting What Doesn't Add UpParanormal statistics: Counting What Doesn't Add Up
Paranormal statistics: Counting What Doesn't Add Up
 
The $path to knowledge: What little it take to unit-test Perl.
The $path to knowledge: What little it take to unit-test Perl.The $path to knowledge: What little it take to unit-test Perl.
The $path to knowledge: What little it take to unit-test Perl.
 
Unit Testing Lots of Perl
Unit Testing Lots of PerlUnit Testing Lots of Perl
Unit Testing Lots of Perl
 
Generating & Querying Calendar Tables in Posgresql
Generating & Querying Calendar Tables in PosgresqlGenerating & Querying Calendar Tables in Posgresql
Generating & Querying Calendar Tables in Posgresql
 
Hypers and Gathers and Takes! Oh my!
Hypers and Gathers and Takes! Oh my!Hypers and Gathers and Takes! Oh my!
Hypers and Gathers and Takes! Oh my!
 
BSDM with BASH: Command Interpolation
BSDM with BASH: Command InterpolationBSDM with BASH: Command Interpolation
BSDM with BASH: Command Interpolation
 
Findbin libs
Findbin libsFindbin libs
Findbin libs
 
Memory Manglement in Raku
Memory Manglement in RakuMemory Manglement in Raku
Memory Manglement in Raku
 
BASH Variables Part 1: Basic Interpolation
BASH Variables Part 1: Basic InterpolationBASH Variables Part 1: Basic Interpolation
BASH Variables Part 1: Basic Interpolation
 
Effective Benchmarks
Effective BenchmarksEffective Benchmarks
Effective Benchmarks
 
Metadata-driven Testing
Metadata-driven TestingMetadata-driven Testing
Metadata-driven Testing
 
The W-curve and its application.
The W-curve and its application.The W-curve and its application.
The W-curve and its application.
 
Keeping objects healthy with Object::Exercise.
Keeping objects healthy with Object::Exercise.Keeping objects healthy with Object::Exercise.
Keeping objects healthy with Object::Exercise.
 
Perl6 Regexen: Reduce the line noise in your code.
Perl6 Regexen: Reduce the line noise in your code.Perl6 Regexen: Reduce the line noise in your code.
Perl6 Regexen: Reduce the line noise in your code.
 
Smoking docker
Smoking dockerSmoking docker
Smoking docker
 
Getting Testy With Perl6
Getting Testy With Perl6Getting Testy With Perl6
Getting Testy With Perl6
 
Neatly Hashing a Tree: FP tree-fold in Perl5 & Perl6
Neatly Hashing a Tree: FP tree-fold in Perl5 & Perl6Neatly Hashing a Tree: FP tree-fold in Perl5 & Perl6
Neatly Hashing a Tree: FP tree-fold in Perl5 & Perl6
 
Neatly folding-a-tree
Neatly folding-a-treeNeatly folding-a-tree
Neatly folding-a-tree
 
Light my-fuse
Light my-fuseLight my-fuse
Light my-fuse
 

Dernier

What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 

Dernier (20)

What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 

Object Trampoline

  • 1. Object::Trampoline  When having not the object you want  is what you need. Steven Lembark <lembark@wrkhors.com>
  • 2. Er... what's “trampoline” object? ● Trampolines not the object you want. ● They are a proxy for the constructor of another  object – the one you want. ● Their behavior is replacing themselves when you  call a method on them. ● Aside from calling a separate constructor, the user  shouldn't know the trampoline ever existed.
  • 3. Why bother? ● When you don't want an object until you need it: – Connections to servers that not always used/available  (e.g., during development or unit testing). – Avoid construcing expensive, seldom­used objects. –  Delay connections to back­end servers until necessary. ● Think of starting up a heavily­forked apache server  and not bringing your database to its knees. ● Or not parsing really large XML until you use it.
  • 4. WARNING: The code you are about to see  contains graphic AUTOLOAD,  literal blessing, and re­ assignment of stack variables. Parenthetical discresion is  advised.
  • 5. How do you bounce an object? ● Easily, in Perl (pity the poor slobs using Java!). – Perl's AUTOLOAD mechanism allows you to intercept  method calls cleanly. – Passing arguments by reference allows replacing them on  the stack: assigning to $_[0] gives your caller a new  object on the fly. – “goto &sub” replaces one call with another. ● Result:  a re­dispatched call with a new object.
  • 6. Co­Operating Classes ● The Object::Trampoline (“O::T”) module uses two  classes: a constructor and dispatcher. ● O::T itself is nothing but an AUTOLOAD. ● It returns a closure blessed into  Object::Trampoline::Bounce (“O::T::B”). ● O::T::B is nothing but (surprise!) an AUTOLOAD.  ● O::T::B replaces the object, re­dispatches the call.
  • 7. Replacing an Object ● O::T::B::AUTOLOAD begins by replacing the stack  argument with the result of running itself: $_[0] = $_[0]­>(); ● This replaces the caller's copy of the object with a  delayed call to the constructor. ● This new object is then used to locate the  requested subroutine via “can”.
  • 8. Using Object::Trampoline ● The difference you'll see in using a trampoline  object is in the constructor. ● The 'real' class becomes the first argument, and  “Object::Trampoline” becomes the new class: my $dbh = DBI­>connect( $dsn,@argz); becomes: my $dbh = Object::Tram poline ‑>connect ( 'DBI', $dsn, @argz );
  • 9. Under the hood ● O::T's AUTOLOAD handles the construction by  blessing a closure that does the real work: my ( undef, $class, @argz ) = @_; my $meth = ( split $AUTOLOAD, '::' )[­1]; my $sub  = sub { $class­>$meth( @argz ) }; bless $sub, 'Object::Trampoline::Bounce'
  • 10. Using the object ● At this point the caller gets back what looks like an  ordinary object: # $dbh starts out as a trampoline my $dbh =  Object::Trampoline‑>connect( 'DBI', ... ); # the method call converts it to a DBI object. my $sth = $dbh­>prepare( ... ); # from this point on there's no way to tell  # that $dbh wasn't a DBI object all along.
  • 11. Converting the Object ● The assignment to $_[0] is made in  O::T::B::AUTOLOAD. ● If $_[0]­>can( $method ) then it uses goto,  otherwise it has to try $_[0]­>$method( @argz ) and  hope for the best (e.g., another AUTOLOAD). ● It also has contains a stub DESTROY to avoid  constructing objects when the go out of scope.
  • 13. But wait, there's more! ● What if requiring the module is the expensive part? ● You want to delay the “use” until necessary, not just  the construction? ● Object::Trampoline::Use does exactly that: my sub = sub {     eval “package $caller; use $class;     $class­>$method( @argz ) };
  • 14. Why use a closure? ● I could have stored the arguments in a hash, with  $object­>{ class } and $object­>{ arguments }. ● But then there would be a difference in handling  different objects that came from O::T or O::T::U. ● The closure allows each handler class to handle the  construction its own way without to specialize  O::T::B for each of them.
  • 15. Example: Server Handles ● Centralizing the data for your server handles can be  helpful. ● All of the mess for describing DBI, Syslog, HTTP,  SOAP... connections can be pushed into one place. ● Catch: Not all of the servers are always available, or  necessary. ● Fix: Export trampolines.
  • 16. Server::Handles package Server::Handle; use Server::Configure qw ( dbi_user ... syslog_server ... ); my %handlerz = ( dbh     => Object::Trampoline‑>connect( 'DBI', ... ), syslogh => Object::Trampoline‑>openlog( 'Syslog::Wrapper', ... ), ); sub import {    # push the handlers out as­is via *$glob = $value.    # the values are shared and the first place they are    # used bounces them for the entire process }
  • 17. Trampoline as a Factory ● This cannot be avoided, therefore it is a feature. ● Unwrapping the stack into a lexical before calling a  method on the trampoline updates the lexical, not  the caller's copy. $foo­>my_wrapper; sub my_wrapper {     my $obj    = shift; # my_wrapper copy of $foo     $obj­>some_method;  # updates $obj, not $foo
  • 18. Caveat Utilitor ● Trampoline objects can only dispatch methods. ● If your object is tied then it'll blow up if you try to  access its tied interface: – $dbh­>{ AutoCommit } = 0; # dies here for trampoline ● None of the ways around this are transparent to the  user, but even with DBI the simple fix is to use  methods to configure the object.
  • 19. “ref” is not a method ● Until a method is called, “ref $object” will give you  “Object::Trampoline::Bounce” and “reftype” will  give you back “CODE”. ● This mainly affects the use of inside­out data, since  $object_data{ refaddr $object } will change after the  first method call.
  • 20. Prototypes are Evil. ● Notice the closure:                                                                 $class­>$constructor( @argz ) ● Defining $constructor with a prototype of ($$) will  break even if you have two values in @argz! ● <soapbox>                                                                Add code or use Class::Contract (whatever) to  actually validate the arguments. Breaking Perl's  calling convention only causes pain.          </soapbox>.