SlideShare une entreprise Scribd logo
1  sur  35
Télécharger pour lire hors ligne
Object::Trampoline
 Why having not the object you want 
is just what you need.
Steven Lembark
Workhorse Computing
lembark@wrkhors.com
We've all been there
Starting the web server crashes your database.
Testing requires working handles for services you don't test.
Compiling error messages in 15 languages you never use.
Patterns: Ways to Scratch an Itch
Language-specific, idiomatic solutions.
Meta-data about language strengths, limitations.
Example: C patterns are about pointers and string handling.
Perl patterns here: objects, dispatch, and stack manglement.
Pattern: “Lazy Initialization”
Separate “construction” and “initialization”.
You only need to construct an object to dispatch with it.
Delay initialization until methods are called.
Common way: If-logic
Construct a naked object.
Check object contents within every method, overload, ...
Works until someone forgets to check...
… or benchmarks the overhead of checking.
Other ways:
Use a factory class to construct a new object every time.
Hard to maintain state across calls.
Use a cached connection (e.g., DBI::connect_cached).
Expensive: check what you know to be true every time.
Not lazy or impatient.
Pattern: Trampoline Class
Simplest approach: co-operating classes with re-bless.
Construct the object in one class.
Bless it into the “bounce class”.
Bounce class initializes the object.
Re-bless the object where it belongs.
Warning:Warning:
Code shown here containsCode shown here contains
graphicgraphic AUTOLOAD's, AUTOLOAD's,
un­filtered bless,un­filtered bless,
& hard­wired stack.& hard­wired stack.
Parenthetical Parenthetical discretiondiscretion is advised. is advised.
Example: Multi-stage initialization
package Foo;package Foo;
## new calls the constructor, re-blesses thenew calls the constructor, re-blesses the
## object then stores the initialize data.object then stores the initialize data.
sub newsub new
{{
my $obj =my $obj = bless &construct,bless &construct, ''Foo::BounceFoo::Bounce';';
$initz{ refaddr $obj } = [ @_ ];$initz{ refaddr $obj } = [ @_ ];
$obj$obj
}}
Example: Multi-stage initialization
package Foo::Bounce;package Foo::Bounce;
AUTOLOADAUTOLOAD
{{
......
## reset the class, lazy initializereset the class, lazy initialize
bless $obj, 'Foo';bless $obj, 'Foo';
my $argzmy $argz = delete $initz{ refaddr $obj };= delete $initz{ refaddr $obj };
$obj->initialize( @$argz );$obj->initialize( @$argz );
goto &{ $object->can( $method ) }goto &{ $object->can( $method ) }
}}
Problem: Co-operating classes require classes.
Hard to add after the fact.
What if you can't re-write the class?
Wrapping every single class is not an option.
A generic solution is the only reasonable fix.
Another Pattern: “Flyweight Object”
Cheap to construct.
Stand-in in for a bulky, expensive object.
Example: Surrogate keys, Unix file descriptors.
Like references or pointers, managed by user code.
Flyweight: Trampoline Object
Replaces itself with another object.
Temporary stand-in for the “real” object.
Only behavior: creating a new object and re-dispatching.
Pass trough the class/object once.
How is it done?
Quite easily:
AUTOLOAD's can intercept method calls cleanly.
References modify the object in place.
goto &sub replaces a call on the stack.
Result: Method re-dispatched with a newly-minted object.
No if-logic, no re-construction, no key-magic.
Click to add code
The “Foo::Bar”
class...
my $obj =my $obj = Foo::BarFoo::Bar->foobar->foobar
((
qw( bim bam )qw( bim bam )
););
The “Foo::Bar”
class...
… becomes an
argument.
my $obj =my $obj = Foo::BarFoo::Bar->frob->frob
((
qw( bim bam )qw( bim bam )
););
my $obj =my $obj = Object::TrampolineObject::Trampoline->frob->frob
((
qw(qw( Foo::BarFoo::Bar bim bam )bim bam )
););
Click to add code
What you knead
Object::Trampoline is nothing but an AUTOLOAD.
Blesses a subref into Object::Trampoline::Bounce.
Yes, Virginia, Perl can bless something other than a hash.
Construct a bouncing object
package Object::Trampoline;package Object::Trampoline;
AUTOLOADAUTOLOAD
{{
shift;shift;
my ( $protomy ( $proto, @argz ) = @_;, @argz ) = @_;
my $methodmy $method = ( split /::/, $AUTOLOAD )[ -1 ];= ( split /::/, $AUTOLOAD )[ -1 ];
my $objmy $obj == sub { $proto->$method( @argz ) }sub { $proto->$method( @argz ) };;
bless $obj, 'bless $obj, 'Object::Trampoline::BounceObject::Trampoline::Bounce''
}}
Bouncing the object
Call the constructor: $_[0] = $_[0]->();
At this point it is no longer a Trampoline object.
AUTOLOAD deals with the method call.
Needs a stub DESTROY to avoid creating the object.
And, Viola!, the object you wanted.
AUTOLOADAUTOLOAD
{{
## assign $_[0] replaces caller's object.assign $_[0] replaces caller's object.
$_[0] = $_[0]->();$_[0] = $_[0]->();
my $class = blessed $_[0];my $class = blessed $_[0];
my $method = ( split /::/, $AUTOLOAD )[ -1 ];my $method = ( split /::/, $AUTOLOAD )[ -1 ];
local $a = $class->can( $method ) ) and goto &$a;local $a = $class->can( $method ) ) and goto &$a;
my $obj = shift;my $obj = shift;
$obj->$method( @_ )$obj->$method( @_ )
}}
DESTROY {}DESTROY {}
Override UNIVERSAL
All classes inherit DOES, VERSION, isa, can.
This means that the AUTOLOAD will not intercept them.
Fix: Overload UNIVERSAL methods to use AUTOLOAD.
Override UNIVERSAL
for my $name ( keys %{for my $name ( keys %{ $::{ 'UNIVERSAL::' }$::{ 'UNIVERSAL::' } } )} )
{{
*{ qualify_to_ref $name }*{ qualify_to_ref $name }
= sub= sub
{{
$AUTOLOAD = $name;$AUTOLOAD = $name;
goto &AUTOLOADgoto &AUTOLOAD
};};
}}
Extra-Bouncy: Object::Trampoline::Use
There are times when using the module is important.
Object::Trampoline::Use does a string eval.
Pushes a “use $package” into the caller's class.
Accommodates side-effects of import in the correct module.
Lazy “use”
AUTOLOADAUTOLOAD
{{
......
my $sub =my $sub =
subsub
{{
eval "package $caller; use $class” or croak ...or croak ...
$class->$method( @argz )$class->$method( @argz )
};};
bless $sub, 'bless $sub, 'Object::Trampoline::BounceObject::Trampoline::Bounce''
}}
Hence a subref:
Object::Trampoline::Bounce has no idea what the sub does.
Encapsulation gives a better division of labor:
One class knows what gets done, O::T::B does it reliably.
Any class that wants to can use O::T::B.
Feeding the Industrial Revolution
Shifted off the stack, lexical copies are replaced in-place.
Trivial to use Trampolines as factory classes.
Annoying if you don't plan correctly.
Shifting without factories
Data::Alias simplifies shifting objects off the stack:
alias my $obj = shift;
The “alias” leaves $obj as a reference to the original.
After that trampolines will do the right thing.
Example: Dealing with handles.
O::T originally developed for a call-center system.
DBI to query pending trouble tickets.
Asterisk to dial out to the group assigned to handle a ticket.
SIP to originate the calls.
Berkeley DB handle to query Asterisk status.
Testing complicated by unnecessary servers.
Fix was trampolines.
Sharing is caring
The server handles were installed from a common module.
Singleton handles update in place on use.
Testing only requires the handles actually exercised.
Sharing a handle
my %handlz =my %handlz =
((
dbhdbh => Object::Trampoline->new( @dbi_argz ),=> Object::Trampoline->new( @dbi_argz ),
sip_hsip_h => Object::Trampoline->new( @sip_argz ),=> Object::Trampoline->new( @sip_argz ),
......
););
sub importsub import
{{
my $callermy $caller = caller;= caller;
for my $name ( @_ )for my $name ( @_ )
{{
*{ qualify_to_ref $name, $caller }*{ qualify_to_ref $name, $caller } = $handlz{ $name };= $handlz{ $name };
}}
returnreturn
}}
Better Errors
Bad Error: “Error: File not found.”
Also Bad: “Error: xyz.config not found”
Fix: pre-check the files, reporting the working directory.
Add error messages with full paths, failure reasons.
Fix: codref blessed into O::T::Bounce.
Finding sanity
packagepackage Sane::FooSane::Foo
sub newsub new
{{
my $pathmy $path = shift;= shift;
bless subbless sub
{{
my $cwdmy $cwd = getcwd;= getcwd;
-e $path-e $path or die "Non-existant: '$path' ($cwd)";or die "Non-existant: '$path' ($cwd)";
-r _-r _ or die "Non-readable: '$path' ($cwd)";or die "Non-readable: '$path' ($cwd)";
......
Foo->new( $path )Foo->new( $path )
},},
'Object::Trampoline::Bounce''Object::Trampoline::Bounce'
}}
Automatic checking
Sane::Foo flyweight does the checking automatically.
Object::Trampoline::Bounce executes the object.
No outside data required: Just the closure.
Returns a Foo object after pre-check.
Trivial to add $$ check for crossing process boundarys.
Sufficiently developed technology...
Misguided magic:
Anyone who violates encapsulation gets what they deserve...
… or the objects have to be tied and overloaded.
Accidental factory objects.
Relying too early on import side-effects w/ O::T::Use.
References
On CPAN:
O::T is ~30 lines of code, 300 lines of POD & comments.
Alternative solutions:
Data::Thunk, Scalar::Defer, Data::Lazy.
Questions?

Contenu connexe

Tendances

BSDM with BASH: Command Interpolation
BSDM with BASH: Command InterpolationBSDM with BASH: Command Interpolation
BSDM with BASH: Command InterpolationWorkhorse 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
 
Ethiopian multiplication in Perl6
Ethiopian multiplication in Perl6Ethiopian multiplication in Perl6
Ethiopian multiplication in Perl6Workhorse 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
 
Replacing "exec" with a type and provider: Return manifests to a declarative ...
Replacing "exec" with a type and provider: Return manifests to a declarative ...Replacing "exec" with a type and provider: Return manifests to a declarative ...
Replacing "exec" with a type and provider: Return manifests to a declarative ...Puppet
 
Barely Legal Xxx Perl Presentation
Barely Legal Xxx Perl PresentationBarely Legal Xxx Perl Presentation
Barely Legal Xxx Perl PresentationAttila Balazs
 
Static Optimization of PHP bytecode (PHPSC 2017)
Static Optimization of PHP bytecode (PHPSC 2017)Static Optimization of PHP bytecode (PHPSC 2017)
Static Optimization of PHP bytecode (PHPSC 2017)Nikita Popov
 
November Camp - Spec BDD with PHPSpec 2
November Camp - Spec BDD with PHPSpec 2November Camp - Spec BDD with PHPSpec 2
November Camp - Spec BDD with PHPSpec 2Kacper Gunia
 
Typed Properties and more: What's coming in PHP 7.4?
Typed Properties and more: What's coming in PHP 7.4?Typed Properties and more: What's coming in PHP 7.4?
Typed Properties and more: What's coming in PHP 7.4?Nikita Popov
 
Melhorando sua API com DSLs
Melhorando sua API com DSLsMelhorando sua API com DSLs
Melhorando sua API com DSLsAugusto Pascutti
 
Puppet Camp Paris 2015: Power of Puppet 4 (Beginner)
Puppet Camp Paris 2015: Power of Puppet 4 (Beginner) Puppet Camp Paris 2015: Power of Puppet 4 (Beginner)
Puppet Camp Paris 2015: Power of Puppet 4 (Beginner) Puppet
 
Perl web frameworks
Perl web frameworksPerl web frameworks
Perl web frameworksdiego_k
 
Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"Fwdays
 

Tendances (20)

Getting Testy With Perl6
Getting Testy With Perl6Getting Testy With Perl6
Getting Testy With Perl6
 
Memory Manglement in Raku
Memory Manglement in RakuMemory Manglement in Raku
Memory Manglement in Raku
 
Smoking docker
Smoking dockerSmoking docker
Smoking docker
 
BSDM with BASH: Command Interpolation
BSDM with BASH: Command InterpolationBSDM with BASH: Command Interpolation
BSDM with BASH: Command Interpolation
 
Unit Testing Lots of Perl
Unit Testing Lots of PerlUnit Testing Lots of Perl
Unit Testing Lots of Perl
 
Getting testy with Perl
Getting testy with PerlGetting testy with Perl
Getting testy with Perl
 
Effective Benchmarks
Effective BenchmarksEffective Benchmarks
Effective Benchmarks
 
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.
 
Ethiopian multiplication in Perl6
Ethiopian multiplication in Perl6Ethiopian multiplication in Perl6
Ethiopian multiplication in 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
 
Replacing "exec" with a type and provider: Return manifests to a declarative ...
Replacing "exec" with a type and provider: Return manifests to a declarative ...Replacing "exec" with a type and provider: Return manifests to a declarative ...
Replacing "exec" with a type and provider: Return manifests to a declarative ...
 
Barely Legal Xxx Perl Presentation
Barely Legal Xxx Perl PresentationBarely Legal Xxx Perl Presentation
Barely Legal Xxx Perl Presentation
 
Static Optimization of PHP bytecode (PHPSC 2017)
Static Optimization of PHP bytecode (PHPSC 2017)Static Optimization of PHP bytecode (PHPSC 2017)
Static Optimization of PHP bytecode (PHPSC 2017)
 
Troubleshooting Puppet
Troubleshooting PuppetTroubleshooting Puppet
Troubleshooting Puppet
 
November Camp - Spec BDD with PHPSpec 2
November Camp - Spec BDD with PHPSpec 2November Camp - Spec BDD with PHPSpec 2
November Camp - Spec BDD with PHPSpec 2
 
Typed Properties and more: What's coming in PHP 7.4?
Typed Properties and more: What's coming in PHP 7.4?Typed Properties and more: What's coming in PHP 7.4?
Typed Properties and more: What's coming in PHP 7.4?
 
Melhorando sua API com DSLs
Melhorando sua API com DSLsMelhorando sua API com DSLs
Melhorando sua API com DSLs
 
Puppet Camp Paris 2015: Power of Puppet 4 (Beginner)
Puppet Camp Paris 2015: Power of Puppet 4 (Beginner) Puppet Camp Paris 2015: Power of Puppet 4 (Beginner)
Puppet Camp Paris 2015: Power of Puppet 4 (Beginner)
 
Perl web frameworks
Perl web frameworksPerl web frameworks
Perl web frameworks
 
Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"
 

En vedette

Analisis Chaid Sebagai Alat Bantu Statistika Untuk (Vita & Dessy)
Analisis Chaid Sebagai Alat Bantu Statistika Untuk (Vita & Dessy)Analisis Chaid Sebagai Alat Bantu Statistika Untuk (Vita & Dessy)
Analisis Chaid Sebagai Alat Bantu Statistika Untuk (Vita & Dessy)arditasukma
 
Aligning seqeunces with W-curve and SQL.
Aligning seqeunces with W-curve and SQL.Aligning seqeunces with W-curve and SQL.
Aligning seqeunces with W-curve and SQL.Workhorse Computing
 
Selenium sandwich-3: Being where you aren't.
Selenium sandwich-3: Being where you aren't.Selenium sandwich-3: Being where you aren't.
Selenium sandwich-3: Being where you aren't.Workhorse Computing
 

En vedette (9)

Digital Age 2.0 - Andrea Harrison
Digital Age 2.0 - Andrea HarrisonDigital Age 2.0 - Andrea Harrison
Digital Age 2.0 - Andrea Harrison
 
Analisis Chaid Sebagai Alat Bantu Statistika Untuk (Vita & Dessy)
Analisis Chaid Sebagai Alat Bantu Statistika Untuk (Vita & Dessy)Analisis Chaid Sebagai Alat Bantu Statistika Untuk (Vita & Dessy)
Analisis Chaid Sebagai Alat Bantu Statistika Untuk (Vita & Dessy)
 
Aligning seqeunces with W-curve and SQL.
Aligning seqeunces with W-curve and SQL.Aligning seqeunces with W-curve and SQL.
Aligning seqeunces with W-curve and SQL.
 
Selenium sandwich-3: Being where you aren't.
Selenium sandwich-3: Being where you aren't.Selenium sandwich-3: Being where you aren't.
Selenium sandwich-3: Being where you aren't.
 
Memory unmanglement
Memory unmanglementMemory unmanglement
Memory unmanglement
 
Lies, Damn Lies, and Benchmarks
Lies, Damn Lies, and BenchmarksLies, Damn Lies, and Benchmarks
Lies, Damn Lies, and Benchmarks
 
Signal Stacktrace
Signal StacktraceSignal Stacktrace
Signal Stacktrace
 
Clustering Genes: W-curve + TSP
Clustering Genes: W-curve + TSPClustering Genes: W-curve + TSP
Clustering Genes: W-curve + TSP
 
A-Walk-on-the-W-Side
A-Walk-on-the-W-SideA-Walk-on-the-W-Side
A-Walk-on-the-W-Side
 

Similaire à Object Trampoline: Why having not the object you want is what you need.

JavaScript(Es5) Interview Questions & Answers
JavaScript(Es5)  Interview Questions & AnswersJavaScript(Es5)  Interview Questions & Answers
JavaScript(Es5) Interview Questions & AnswersRatnala Charan kumar
 
Zend framework 03 - singleton factory data mapper caching logging
Zend framework 03 - singleton factory data mapper caching loggingZend framework 03 - singleton factory data mapper caching logging
Zend framework 03 - singleton factory data mapper caching loggingTricode (part of Dept)
 
Oops concepts in php
Oops concepts in phpOops concepts in php
Oops concepts in phpCPD INDIA
 
Building Testable PHP Applications
Building Testable PHP ApplicationsBuilding Testable PHP Applications
Building Testable PHP Applicationschartjes
 
Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...go_oh
 
SystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features SummarySystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features SummaryAmal Khailtash
 
Python magicmethods
Python magicmethodsPython magicmethods
Python magicmethodsdreampuf
 
Perl Teach-In (part 2)
Perl Teach-In (part 2)Perl Teach-In (part 2)
Perl Teach-In (part 2)Dave Cross
 
Prototype Utility Methods(1)
Prototype Utility Methods(1)Prototype Utility Methods(1)
Prototype Utility Methods(1)mussawir20
 
iPhone Seminar Part 2
iPhone Seminar Part 2iPhone Seminar Part 2
iPhone Seminar Part 2NAILBITER
 
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
 
The Naked Bundle - Symfony Live London 2014
The Naked Bundle - Symfony Live London 2014The Naked Bundle - Symfony Live London 2014
The Naked Bundle - Symfony Live London 2014Matthias Noback
 

Similaire à Object Trampoline: Why having not the object you want is what you need. (20)

JavaScript(Es5) Interview Questions & Answers
JavaScript(Es5)  Interview Questions & AnswersJavaScript(Es5)  Interview Questions & Answers
JavaScript(Es5) Interview Questions & Answers
 
OOP in PHP.pptx
OOP in PHP.pptxOOP in PHP.pptx
OOP in PHP.pptx
 
Zend framework 03 - singleton factory data mapper caching logging
Zend framework 03 - singleton factory data mapper caching loggingZend framework 03 - singleton factory data mapper caching logging
Zend framework 03 - singleton factory data mapper caching logging
 
iOS Session-2
iOS Session-2iOS Session-2
iOS Session-2
 
Python advance
Python advancePython advance
Python advance
 
Oops concepts in php
Oops concepts in phpOops concepts in php
Oops concepts in php
 
Building Testable PHP Applications
Building Testable PHP ApplicationsBuilding Testable PHP Applications
Building Testable PHP Applications
 
Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...
 
SystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features SummarySystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features Summary
 
Python magicmethods
Python magicmethodsPython magicmethods
Python magicmethods
 
Objective c
Objective cObjective c
Objective c
 
Perl Teach-In (part 2)
Perl Teach-In (part 2)Perl Teach-In (part 2)
Perl Teach-In (part 2)
 
Prototype Utility Methods(1)
Prototype Utility Methods(1)Prototype Utility Methods(1)
Prototype Utility Methods(1)
 
lab4_php
lab4_phplab4_php
lab4_php
 
lab4_php
lab4_phplab4_php
lab4_php
 
iPhone Seminar Part 2
iPhone Seminar Part 2iPhone Seminar Part 2
iPhone Seminar Part 2
 
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
 
Oops concept in php
Oops concept in phpOops concept in php
Oops concept in php
 
The Naked Bundle - Symfony Live London 2014
The Naked Bundle - Symfony Live London 2014The Naked Bundle - Symfony Live London 2014
The Naked Bundle - Symfony Live London 2014
 
Effective PHP. Part 2
Effective PHP. Part 2Effective PHP. Part 2
Effective PHP. Part 2
 

Plus de Workhorse Computing

Plus de Workhorse Computing (14)

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
 
mro-every.pdf
mro-every.pdfmro-every.pdf
mro-every.pdf
 
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
 
Generating & Querying Calendar Tables in Posgresql
Generating & Querying Calendar Tables in PosgresqlGenerating & Querying Calendar Tables in Posgresql
Generating & Querying Calendar Tables in Posgresql
 
The W-curve and its application.
The W-curve and its application.The W-curve and its application.
The W-curve and its application.
 
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
 
Paranormal stats
Paranormal statsParanormal stats
Paranormal stats
 
Shared Object images in Docker: What you need is what you want.
Shared Object images in Docker: What you need is what you want.Shared Object images in Docker: What you need is what you want.
Shared Object images in Docker: What you need is what you want.
 
Putting some "logic" in LVM.
Putting some "logic" in LVM.Putting some "logic" in LVM.
Putting some "logic" in LVM.
 
Selenium sandwich-2
Selenium sandwich-2Selenium sandwich-2
Selenium sandwich-2
 
Selenium Sandwich Part 1: Data driven Selenium
Selenium Sandwich Part 1: Data driven Selenium Selenium Sandwich Part 1: Data driven Selenium
Selenium Sandwich Part 1: Data driven Selenium
 
Docker perl build
Docker perl buildDocker perl build
Docker perl build
 
Designing net-aws-glacier
Designing net-aws-glacierDesigning net-aws-glacier
Designing net-aws-glacier
 

Dernier

Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 

Dernier (20)

Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 

Object Trampoline: Why having not the object you want is what you need.

  • 2. We've all been there Starting the web server crashes your database. Testing requires working handles for services you don't test. Compiling error messages in 15 languages you never use.
  • 3. Patterns: Ways to Scratch an Itch Language-specific, idiomatic solutions. Meta-data about language strengths, limitations. Example: C patterns are about pointers and string handling. Perl patterns here: objects, dispatch, and stack manglement.
  • 4. Pattern: “Lazy Initialization” Separate “construction” and “initialization”. You only need to construct an object to dispatch with it. Delay initialization until methods are called.
  • 5. Common way: If-logic Construct a naked object. Check object contents within every method, overload, ... Works until someone forgets to check... … or benchmarks the overhead of checking.
  • 6. Other ways: Use a factory class to construct a new object every time. Hard to maintain state across calls. Use a cached connection (e.g., DBI::connect_cached). Expensive: check what you know to be true every time. Not lazy or impatient.
  • 7. Pattern: Trampoline Class Simplest approach: co-operating classes with re-bless. Construct the object in one class. Bless it into the “bounce class”. Bounce class initializes the object. Re-bless the object where it belongs.
  • 9. Example: Multi-stage initialization package Foo;package Foo; ## new calls the constructor, re-blesses thenew calls the constructor, re-blesses the ## object then stores the initialize data.object then stores the initialize data. sub newsub new {{ my $obj =my $obj = bless &construct,bless &construct, ''Foo::BounceFoo::Bounce';'; $initz{ refaddr $obj } = [ @_ ];$initz{ refaddr $obj } = [ @_ ]; $obj$obj }}
  • 10. Example: Multi-stage initialization package Foo::Bounce;package Foo::Bounce; AUTOLOADAUTOLOAD {{ ...... ## reset the class, lazy initializereset the class, lazy initialize bless $obj, 'Foo';bless $obj, 'Foo'; my $argzmy $argz = delete $initz{ refaddr $obj };= delete $initz{ refaddr $obj }; $obj->initialize( @$argz );$obj->initialize( @$argz ); goto &{ $object->can( $method ) }goto &{ $object->can( $method ) } }}
  • 11. Problem: Co-operating classes require classes. Hard to add after the fact. What if you can't re-write the class? Wrapping every single class is not an option. A generic solution is the only reasonable fix.
  • 12. Another Pattern: “Flyweight Object” Cheap to construct. Stand-in in for a bulky, expensive object. Example: Surrogate keys, Unix file descriptors. Like references or pointers, managed by user code.
  • 13. Flyweight: Trampoline Object Replaces itself with another object. Temporary stand-in for the “real” object. Only behavior: creating a new object and re-dispatching. Pass trough the class/object once.
  • 14. How is it done? Quite easily: AUTOLOAD's can intercept method calls cleanly. References modify the object in place. goto &sub replaces a call on the stack. Result: Method re-dispatched with a newly-minted object. No if-logic, no re-construction, no key-magic.
  • 15. Click to add code The “Foo::Bar” class... my $obj =my $obj = Foo::BarFoo::Bar->foobar->foobar (( qw( bim bam )qw( bim bam ) ););
  • 16. The “Foo::Bar” class... … becomes an argument. my $obj =my $obj = Foo::BarFoo::Bar->frob->frob (( qw( bim bam )qw( bim bam ) );); my $obj =my $obj = Object::TrampolineObject::Trampoline->frob->frob (( qw(qw( Foo::BarFoo::Bar bim bam )bim bam ) );); Click to add code
  • 17. What you knead Object::Trampoline is nothing but an AUTOLOAD. Blesses a subref into Object::Trampoline::Bounce. Yes, Virginia, Perl can bless something other than a hash.
  • 18. Construct a bouncing object package Object::Trampoline;package Object::Trampoline; AUTOLOADAUTOLOAD {{ shift;shift; my ( $protomy ( $proto, @argz ) = @_;, @argz ) = @_; my $methodmy $method = ( split /::/, $AUTOLOAD )[ -1 ];= ( split /::/, $AUTOLOAD )[ -1 ]; my $objmy $obj == sub { $proto->$method( @argz ) }sub { $proto->$method( @argz ) };; bless $obj, 'bless $obj, 'Object::Trampoline::BounceObject::Trampoline::Bounce'' }}
  • 19. Bouncing the object Call the constructor: $_[0] = $_[0]->(); At this point it is no longer a Trampoline object. AUTOLOAD deals with the method call. Needs a stub DESTROY to avoid creating the object.
  • 20. And, Viola!, the object you wanted. AUTOLOADAUTOLOAD {{ ## assign $_[0] replaces caller's object.assign $_[0] replaces caller's object. $_[0] = $_[0]->();$_[0] = $_[0]->(); my $class = blessed $_[0];my $class = blessed $_[0]; my $method = ( split /::/, $AUTOLOAD )[ -1 ];my $method = ( split /::/, $AUTOLOAD )[ -1 ]; local $a = $class->can( $method ) ) and goto &$a;local $a = $class->can( $method ) ) and goto &$a; my $obj = shift;my $obj = shift; $obj->$method( @_ )$obj->$method( @_ ) }} DESTROY {}DESTROY {}
  • 21. Override UNIVERSAL All classes inherit DOES, VERSION, isa, can. This means that the AUTOLOAD will not intercept them. Fix: Overload UNIVERSAL methods to use AUTOLOAD.
  • 22. Override UNIVERSAL for my $name ( keys %{for my $name ( keys %{ $::{ 'UNIVERSAL::' }$::{ 'UNIVERSAL::' } } )} ) {{ *{ qualify_to_ref $name }*{ qualify_to_ref $name } = sub= sub {{ $AUTOLOAD = $name;$AUTOLOAD = $name; goto &AUTOLOADgoto &AUTOLOAD };}; }}
  • 23. Extra-Bouncy: Object::Trampoline::Use There are times when using the module is important. Object::Trampoline::Use does a string eval. Pushes a “use $package” into the caller's class. Accommodates side-effects of import in the correct module.
  • 24. Lazy “use” AUTOLOADAUTOLOAD {{ ...... my $sub =my $sub = subsub {{ eval "package $caller; use $class” or croak ...or croak ... $class->$method( @argz )$class->$method( @argz ) };}; bless $sub, 'bless $sub, 'Object::Trampoline::BounceObject::Trampoline::Bounce'' }}
  • 25. Hence a subref: Object::Trampoline::Bounce has no idea what the sub does. Encapsulation gives a better division of labor: One class knows what gets done, O::T::B does it reliably. Any class that wants to can use O::T::B.
  • 26. Feeding the Industrial Revolution Shifted off the stack, lexical copies are replaced in-place. Trivial to use Trampolines as factory classes. Annoying if you don't plan correctly.
  • 27. Shifting without factories Data::Alias simplifies shifting objects off the stack: alias my $obj = shift; The “alias” leaves $obj as a reference to the original. After that trampolines will do the right thing.
  • 28. Example: Dealing with handles. O::T originally developed for a call-center system. DBI to query pending trouble tickets. Asterisk to dial out to the group assigned to handle a ticket. SIP to originate the calls. Berkeley DB handle to query Asterisk status. Testing complicated by unnecessary servers. Fix was trampolines.
  • 29. Sharing is caring The server handles were installed from a common module. Singleton handles update in place on use. Testing only requires the handles actually exercised.
  • 30. Sharing a handle my %handlz =my %handlz = (( dbhdbh => Object::Trampoline->new( @dbi_argz ),=> Object::Trampoline->new( @dbi_argz ), sip_hsip_h => Object::Trampoline->new( @sip_argz ),=> Object::Trampoline->new( @sip_argz ), ...... );); sub importsub import {{ my $callermy $caller = caller;= caller; for my $name ( @_ )for my $name ( @_ ) {{ *{ qualify_to_ref $name, $caller }*{ qualify_to_ref $name, $caller } = $handlz{ $name };= $handlz{ $name }; }} returnreturn }}
  • 31. Better Errors Bad Error: “Error: File not found.” Also Bad: “Error: xyz.config not found” Fix: pre-check the files, reporting the working directory. Add error messages with full paths, failure reasons. Fix: codref blessed into O::T::Bounce.
  • 32. Finding sanity packagepackage Sane::FooSane::Foo sub newsub new {{ my $pathmy $path = shift;= shift; bless subbless sub {{ my $cwdmy $cwd = getcwd;= getcwd; -e $path-e $path or die "Non-existant: '$path' ($cwd)";or die "Non-existant: '$path' ($cwd)"; -r _-r _ or die "Non-readable: '$path' ($cwd)";or die "Non-readable: '$path' ($cwd)"; ...... Foo->new( $path )Foo->new( $path ) },}, 'Object::Trampoline::Bounce''Object::Trampoline::Bounce' }}
  • 33. Automatic checking Sane::Foo flyweight does the checking automatically. Object::Trampoline::Bounce executes the object. No outside data required: Just the closure. Returns a Foo object after pre-check. Trivial to add $$ check for crossing process boundarys.
  • 34. Sufficiently developed technology... Misguided magic: Anyone who violates encapsulation gets what they deserve... … or the objects have to be tied and overloaded. Accidental factory objects. Relying too early on import side-effects w/ O::T::Use.
  • 35. References On CPAN: O::T is ~30 lines of code, 300 lines of POD & comments. Alternative solutions: Data::Thunk, Scalar::Defer, Data::Lazy. Questions?