SlideShare una empresa de Scribd logo
1 de 15
Descargar para leer sin conexión
What is Moose?



   man Moose: “A postmodern object system for perl 5.”
   Inspired by Metaobject Protocol of Common Lisp Object System
   (CLOS)
   A partial backport of Perl 6 concepts to Perl 5
   Makes module definition trivial
   Has constraints for checking args to constructors, getters, setters
   Has roles (called ’traits’ in the programming languages literature)
   (A few slides on Test::MockObject at end of talk.)




   Nicholas Dronen ()   Moose, XML::LibXML, and Test::MockObject   November 10, 2009   1 / 15
Defining a constructor: This is your module

    package ModuleWithoutMoose;
    sub new {
        my $proto = shift;
        my $class = ref($proto) || $proto;
        my $self = bless({}, $class);
        my %args = @_;
        # Validate $args{foo}
        $self->{foo} = $args{foo};
        # Validate $args{bar};
        $self->{bar} = $args{bar};
        return $self;
    }
    1;



    Nicholas Dronen ()   Moose, XML::LibXML, and Test::MockObject   November 10, 2009   2 / 15
Defining a constructor: This is your module on Moose




    package ModuleWithMoose;
    use Moose;
    has ’foo’ => (is => ’ro’, isa => ’Str’, required => 1);
    has ’bar’ => (is => ’rw’, isa => ’Num’, required => 1);
    no Moose;
    __PACKAGE__->meta->make_immutable;
    1;




    Nicholas Dronen ()   Moose, XML::LibXML, and Test::MockObject   November 10, 2009   3 / 15
What does that do?




   has creates an attribute (field (Java), member var (C++))
   has creates a getter/setter with same name as the attribute
   is declares the attribute read-only or read-write
   required = 1 means an exception is thrown if arg is not present
   no Moose, make immutable reseal the module (faster)




   Nicholas Dronen ()   Moose, XML::LibXML, and Test::MockObject   November 10, 2009   4 / 15
Using a Moose module (constructor)



   use ModuleWithMoose;

   # OK
   ModuleWithMoose->new(foo => "hello", bar => 2);

   # Dies: type of ’bar’
   ModuleWithMoose->new(foo => "hello", bar => "bad");

   # Dies: ’bar’ required
   ModuleWithMoose->new(foo => "hello");




    Nicholas Dronen ()   Moose, XML::LibXML, and Test::MockObject   November 10, 2009   5 / 15
Using a Moose module (getter/setter)

    use ModuleWithMoose;
    my $o = ModuleWithMoose->new(foo => "hello", bar => 2);

    # Prints "hello"
    print $o->foo();

    # Dies: ’foo’ is red-only
    $o->foo("bad");

    # OK: ’bar’ is writable
    $o->bar(10);

    # Dies: type of ’bar’
    $o->bar("bad");


    Nicholas Dronen ()   Moose, XML::LibXML, and Test::MockObject   November 10, 2009   6 / 15
Attribute initialization



    No guarantee on order of initialization
    This is a problem when one attribute depends on another
    Solution is to use lazy or lazy build
    Simple attributes (scalars or empty refs): default is ok
    Complex attributes (all others): use builder instead
    builder => NAME , where NAME is a method
    Builder method conventionally named build ATTRNAME




    Nicholas Dronen ()   Moose, XML::LibXML, and Test::MockObject   November 10, 2009   7 / 15
Type constraints



    isa => ’Str’ a string (undef illegal)
    isa => ’Maybe[Str]’ a string (undef legal)
    isa => ’ArrayRef[Num]’ an array ref of numbers
    isa => ’ArrayRef[Maybe[Str]]’ an array ref of strings (undef
    legal)
    isa => ’XML::LibXML::Element’ an instance of stated kind
    perldoc Moose::Util::TypeConstraints and perldoc
    Moose::Manual::Types




    Nicholas Dronen ()   Moose, XML::LibXML, and Test::MockObject   November 10, 2009   8 / 15
Validation of arguments to other methods



   Use Moose type constraints to validate args to arbitrary methods
   See MooseX::Params::Validate (not 5.8.2 or 5.10.1 PKT-perl)
   Also see MooseX::Method::Signatures (not in 5.8.2 or 5.10.1
   PKT-perl)

    method morning (Str $name) {
        $self->say("Good morning ${name}!");
    }




    Nicholas Dronen ()   Moose, XML::LibXML, and Test::MockObject   November 10, 2009   9 / 15
Roles



   A role is like an abstract base class, but not a class
   A role is like an interface, but contains code
   Like a mixin in the classical LISP-ian sense, but not in the inheritance
   hierarchy
   Ruby’s mixins are similar
   Inspired by traits
   Larry Wall (Perl 6 objects spec): “Classes are primarily for instance
   management, not code reuse.”




    Nicholas Dronen ()   Moose, XML::LibXML, and Test::MockObject   November 10, 2009   10 / 15
Traits

    Traits: Composable Units of Behavior, ECOOP’2003, LNCS 2743, pp.
    248-274, Springer Verlag, 2003
    “A class has a primary role as a generator of instances.” Not ideal for
    code reuse.
    Single inheritance not flexible enough
    Multiple inheritance has problems (diamond problem, upreferences)
    Interfaces don’t help code reuse; need either multiple implementations
    or a helper class in some cases
    (Classical) mixins are part of single inheritance hierarchy; can’t access
    overridden methods
    Traits have flattening property, are not part of any inheritance
    hierarchy
    Traits make demands of classes (or traits) that use them
    Conflicts in names of traits resolved via aliases
    Nicholas Dronen ()   Moose, XML::LibXML, and Test::MockObject   November 10, 2009   11 / 15
Defining a role

    package Expirable;
    use Moose::Role;
    # Demand that our consumer have ’handle’ and ’name’ method
    requires qw(handle name);
    sub handleWithTimeout {
        my $self = shift;
        # Initialize local variables
        try {
            local $SIG{ALRM} = sub { confess };
            alarm($seconds); $self->handle(%args); alarm(0);
        } catch { # Handle exception };
    }
    no Moose::Role; 1;



    Nicholas Dronen ()   Moose, XML::LibXML, and Test::MockObject   November 10, 2009   12 / 15
Consuming a role




   package ModuleThatCanExpire;
   use Moose;
   # If I have ’handle’ and ’name’ methods, this succeeds,
   # and it gives me a ’handleWithTimeout’ method.
   with ’Expirable’;




    Nicholas Dronen ()   Moose, XML::LibXML, and Test::MockObject   November 10, 2009   13 / 15
Gotchas: Exceptions



   Error module incompatible with Moose
   Both modules export a function named ’with’
   Options
          Try::Tiny
                  Simple implementation
                  Already in 5.8.2 and 5.10.1 PKT-perl
          TryCatch
                  Nicer semantics
                  Can return from a block
                  Adds hooks to the compiler to do the right thing
                  Not in 5.8.2 or 5.10.1 PKT-perl; would be nice for 5.10.1




    Nicholas Dronen ()       Moose, XML::LibXML, and Test::MockObject   November 10, 2009   14 / 15
Test::MockObject

   Unit test: test your code in isolation from all other code
   Problem: references to concrete types (e.g. Foo->new()).
   To attain testability in Java: interfaces, factories, dependency
   injection
   Then use a mock object library (e.g. EasyMock, jMock, others)
   Not so in Perl!
   Test::MockObject allows you to mock out the loader
   Akin to mocking out an import in Java
   Now Foo->new() doesn’t impede unit-testability
   Good for testing legacy code
   Duck typing is nice, but Foo->new() and use Foo are the only
   textual signals you have that you’re actually using a Foo.
   Not in 5.8.2 PKT-perl; in 5.10.1 PKT-perl

   Nicholas Dronen ()   Moose, XML::LibXML, and Test::MockObject   November 10, 2009   15 / 15

Más contenido relacionado

La actualidad más candente

Oral presentation v2
Oral presentation v2Oral presentation v2
Oral presentation v2Yeqi He
 
Kotlin으로 안드로이드 개발하기
Kotlin으로 안드로이드 개발하기Kotlin으로 안드로이드 개발하기
Kotlin으로 안드로이드 개발하기Taehwan kwon
 
Whitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applicationsWhitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applicationsYura Nosenko
 
Clojure made-simple - John Stevenson
Clojure made-simple - John StevensonClojure made-simple - John Stevenson
Clojure made-simple - John StevensonJAX London
 
Testing Spring Boot application in post-JUnit 4 world
Testing Spring Boot application in post-JUnit 4 worldTesting Spring Boot application in post-JUnit 4 world
Testing Spring Boot application in post-JUnit 4 worldYura Nosenko
 
The definitive guide to java agents
The definitive guide to java agentsThe definitive guide to java agents
The definitive guide to java agentsRafael Winterhalter
 
Java Serialization Deep Dive
Java Serialization Deep DiveJava Serialization Deep Dive
Java Serialization Deep DiveMartijn Dashorst
 
Using Java from Ruby with JRuby IRB
Using Java from Ruby with JRuby IRBUsing Java from Ruby with JRuby IRB
Using Java from Ruby with JRuby IRBHiro Asari
 
Spock: Test Well and Prosper
Spock: Test Well and ProsperSpock: Test Well and Prosper
Spock: Test Well and ProsperKen Kousen
 
Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)HamletDRC
 
A Deeper look into Javascript Basics
A Deeper look into Javascript BasicsA Deeper look into Javascript Basics
A Deeper look into Javascript BasicsMindfire Solutions
 
Modern Java Concurrency
Modern Java ConcurrencyModern Java Concurrency
Modern Java ConcurrencyBen Evans
 
Ppl for students unit 4 and 5
Ppl for students unit 4 and 5Ppl for students unit 4 and 5
Ppl for students unit 4 and 5Akshay Nagpurkar
 
The many facets of code reuse in JavaScript
The many facets of code reuse in JavaScriptThe many facets of code reuse in JavaScript
The many facets of code reuse in JavaScriptLeonardo Borges
 
Intro to scala
Intro to scalaIntro to scala
Intro to scalaJoe Zulli
 

La actualidad más candente (20)

Oral presentation v2
Oral presentation v2Oral presentation v2
Oral presentation v2
 
Kotlin으로 안드로이드 개발하기
Kotlin으로 안드로이드 개발하기Kotlin으로 안드로이드 개발하기
Kotlin으로 안드로이드 개발하기
 
The Java memory model made easy
The Java memory model made easyThe Java memory model made easy
The Java memory model made easy
 
Java For Automation
Java   For AutomationJava   For Automation
Java For Automation
 
Whitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applicationsWhitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applications
 
Clojure made-simple - John Stevenson
Clojure made-simple - John StevensonClojure made-simple - John Stevenson
Clojure made-simple - John Stevenson
 
Testing Spring Boot application in post-JUnit 4 world
Testing Spring Boot application in post-JUnit 4 worldTesting Spring Boot application in post-JUnit 4 world
Testing Spring Boot application in post-JUnit 4 world
 
The definitive guide to java agents
The definitive guide to java agentsThe definitive guide to java agents
The definitive guide to java agents
 
Java Serialization Deep Dive
Java Serialization Deep DiveJava Serialization Deep Dive
Java Serialization Deep Dive
 
Using Java from Ruby with JRuby IRB
Using Java from Ruby with JRuby IRBUsing Java from Ruby with JRuby IRB
Using Java from Ruby with JRuby IRB
 
Spock: Test Well and Prosper
Spock: Test Well and ProsperSpock: Test Well and Prosper
Spock: Test Well and Prosper
 
Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)
 
A Deeper look into Javascript Basics
A Deeper look into Javascript BasicsA Deeper look into Javascript Basics
A Deeper look into Javascript Basics
 
JavaScript Basics
JavaScript BasicsJavaScript Basics
JavaScript Basics
 
Modern Java Concurrency
Modern Java ConcurrencyModern Java Concurrency
Modern Java Concurrency
 
Complete Java Course
Complete Java CourseComplete Java Course
Complete Java Course
 
Ppl for students unit 4 and 5
Ppl for students unit 4 and 5Ppl for students unit 4 and 5
Ppl for students unit 4 and 5
 
The many facets of code reuse in JavaScript
The many facets of code reuse in JavaScriptThe many facets of code reuse in JavaScript
The many facets of code reuse in JavaScript
 
Intro to scala
Intro to scalaIntro to scala
Intro to scala
 
Java Threads
Java ThreadsJava Threads
Java Threads
 

Destacado

B12 m from_chno_381790_euro_5_bra_
B12 m from_chno_381790_euro_5_bra_B12 m from_chno_381790_euro_5_bra_
B12 m from_chno_381790_euro_5_bra_Paulo Vieira
 
Moniteur maison-france-confort concept-mfc_2020_nov2010_1
Moniteur maison-france-confort concept-mfc_2020_nov2010_1Moniteur maison-france-confort concept-mfc_2020_nov2010_1
Moniteur maison-france-confort concept-mfc_2020_nov2010_1Yannick Blaser
 
Les outils de financement - PCAET
Les outils de financement - PCAETLes outils de financement - PCAET
Les outils de financement - PCAETALEC_Rennes
 
Pemberian Ubat Parenteral - Suntikan
Pemberian Ubat Parenteral - SuntikanPemberian Ubat Parenteral - Suntikan
Pemberian Ubat Parenteral - SuntikanMuhammad Nasrullah
 
Does a rich GUI make the bank richer?
Does a rich GUI make the bank richer?Does a rich GUI make the bank richer?
Does a rich GUI make the bank richer?Haakon Halvorsen
 
X Jornadas de Gerencia de Riesgos y Emergencias
X Jornadas de Gerencia de Riesgos y EmergenciasX Jornadas de Gerencia de Riesgos y Emergencias
X Jornadas de Gerencia de Riesgos y EmergenciasMertxe J. Badiola
 
Patrimoine immobilier des années 50-70 / l'innovation, une réponse aux contra...
Patrimoine immobilier des années 50-70 / l'innovation, une réponse aux contra...Patrimoine immobilier des années 50-70 / l'innovation, une réponse aux contra...
Patrimoine immobilier des années 50-70 / l'innovation, une réponse aux contra...Novabuild
 
Efficacité énergétique des bâtiments, mesures, performances et conséquences s...
Efficacité énergétique des bâtiments, mesures, performances et conséquences s...Efficacité énergétique des bâtiments, mesures, performances et conséquences s...
Efficacité énergétique des bâtiments, mesures, performances et conséquences s...The Shift Project
 
Tindakan farmakodinamik & farmakokinetik
Tindakan farmakodinamik & farmakokinetikTindakan farmakodinamik & farmakokinetik
Tindakan farmakodinamik & farmakokinetikMuhammad Nasrullah
 
Pemberian Ubat Melalui Suntikan Intradermal
Pemberian Ubat Melalui Suntikan IntradermalPemberian Ubat Melalui Suntikan Intradermal
Pemberian Ubat Melalui Suntikan IntradermalMuhammad Nasrullah
 
Non-Steroidal Anti-Inflammatory Drugs (NSAIDs)
Non-Steroidal Anti-Inflammatory Drugs (NSAIDs)Non-Steroidal Anti-Inflammatory Drugs (NSAIDs)
Non-Steroidal Anti-Inflammatory Drugs (NSAIDs)Muhammad Nasrullah
 
Simulation thermique dynamique
Simulation thermique dynamiqueSimulation thermique dynamique
Simulation thermique dynamiquePatriciaLesage
 

Destacado (20)

Temas de medicina de emergencias y trauma
Temas de medicina de emergencias y traumaTemas de medicina de emergencias y trauma
Temas de medicina de emergencias y trauma
 
B12 m from_chno_381790_euro_5_bra_
B12 m from_chno_381790_euro_5_bra_B12 m from_chno_381790_euro_5_bra_
B12 m from_chno_381790_euro_5_bra_
 
amp_operacionales
amp_operacionalesamp_operacionales
amp_operacionales
 
Moniteur maison-france-confort concept-mfc_2020_nov2010_1
Moniteur maison-france-confort concept-mfc_2020_nov2010_1Moniteur maison-france-confort concept-mfc_2020_nov2010_1
Moniteur maison-france-confort concept-mfc_2020_nov2010_1
 
ASTRONOMIA MUHYSCA
ASTRONOMIA MUHYSCAASTRONOMIA MUHYSCA
ASTRONOMIA MUHYSCA
 
Les outils de financement - PCAET
Les outils de financement - PCAETLes outils de financement - PCAET
Les outils de financement - PCAET
 
Aerogenerador
AerogeneradorAerogenerador
Aerogenerador
 
Réglementation par le CSTB
Réglementation par le CSTBRéglementation par le CSTB
Réglementation par le CSTB
 
Resumen
ResumenResumen
Resumen
 
Pemberian Ubat Parenteral - Suntikan
Pemberian Ubat Parenteral - SuntikanPemberian Ubat Parenteral - Suntikan
Pemberian Ubat Parenteral - Suntikan
 
Does a rich GUI make the bank richer?
Does a rich GUI make the bank richer?Does a rich GUI make the bank richer?
Does a rich GUI make the bank richer?
 
X Jornadas de Gerencia de Riesgos y Emergencias
X Jornadas de Gerencia de Riesgos y EmergenciasX Jornadas de Gerencia de Riesgos y Emergencias
X Jornadas de Gerencia de Riesgos y Emergencias
 
Patrimoine immobilier des années 50-70 / l'innovation, une réponse aux contra...
Patrimoine immobilier des années 50-70 / l'innovation, une réponse aux contra...Patrimoine immobilier des années 50-70 / l'innovation, une réponse aux contra...
Patrimoine immobilier des années 50-70 / l'innovation, une réponse aux contra...
 
PEMBERIAN UBAT SECARA ORAL
PEMBERIAN UBAT SECARA ORALPEMBERIAN UBAT SECARA ORAL
PEMBERIAN UBAT SECARA ORAL
 
Efficacité énergétique des bâtiments, mesures, performances et conséquences s...
Efficacité énergétique des bâtiments, mesures, performances et conséquences s...Efficacité énergétique des bâtiments, mesures, performances et conséquences s...
Efficacité énergétique des bâtiments, mesures, performances et conséquences s...
 
Tindakan farmakodinamik & farmakokinetik
Tindakan farmakodinamik & farmakokinetikTindakan farmakodinamik & farmakokinetik
Tindakan farmakodinamik & farmakokinetik
 
PEMBERIAN UBAT PARENTERAL
PEMBERIAN UBAT PARENTERALPEMBERIAN UBAT PARENTERAL
PEMBERIAN UBAT PARENTERAL
 
Pemberian Ubat Melalui Suntikan Intradermal
Pemberian Ubat Melalui Suntikan IntradermalPemberian Ubat Melalui Suntikan Intradermal
Pemberian Ubat Melalui Suntikan Intradermal
 
Non-Steroidal Anti-Inflammatory Drugs (NSAIDs)
Non-Steroidal Anti-Inflammatory Drugs (NSAIDs)Non-Steroidal Anti-Inflammatory Drugs (NSAIDs)
Non-Steroidal Anti-Inflammatory Drugs (NSAIDs)
 
Simulation thermique dynamique
Simulation thermique dynamiqueSimulation thermique dynamique
Simulation thermique dynamique
 

Similar a Moose

Moose: Perl Objects
Moose: Perl ObjectsMoose: Perl Objects
Moose: Perl ObjectsLambert Lum
 
Lombok Features
Lombok FeaturesLombok Features
Lombok Features文峰 眭
 
Introduction to Ecmascript - ES6
Introduction to Ecmascript - ES6Introduction to Ecmascript - ES6
Introduction to Ecmascript - ES6Nilesh Jayanandana
 
Clojure for Java developers
Clojure for Java developersClojure for Java developers
Clojure for Java developersJohn Stevenson
 
JRuby e DSL
JRuby e DSLJRuby e DSL
JRuby e DSLjodosha
 
Introduction to clojure
Introduction to clojureIntroduction to clojure
Introduction to clojureAbbas Raza
 
JavaScript Miller Columns
JavaScript Miller ColumnsJavaScript Miller Columns
JavaScript Miller ColumnsJonathan Fine
 
A tour on ruby and friends
A tour on ruby and friendsA tour on ruby and friends
A tour on ruby and friends旻琦 潘
 
TorqueBox: The beauty of Ruby with the power of JBoss. Presented at Devnexus...
TorqueBox: The beauty of Ruby with the power of JBoss.  Presented at Devnexus...TorqueBox: The beauty of Ruby with the power of JBoss.  Presented at Devnexus...
TorqueBox: The beauty of Ruby with the power of JBoss. Presented at Devnexus...bobmcwhirter
 
Macruby - RubyConf Presentation 2010
Macruby - RubyConf Presentation 2010Macruby - RubyConf Presentation 2010
Macruby - RubyConf Presentation 2010Matt Aimonetti
 
Future Programming Language
Future Programming LanguageFuture Programming Language
Future Programming LanguageYLTO
 
Real world cross-platform testing
Real world cross-platform testingReal world cross-platform testing
Real world cross-platform testingPeter Edwards
 
Groovy Metaprogramming for Dummies
Groovy Metaprogramming for DummiesGroovy Metaprogramming for Dummies
Groovy Metaprogramming for DummiesDarren Cruse
 
Coroutines for Kotlin Multiplatform in Practise
Coroutines for Kotlin Multiplatform in PractiseCoroutines for Kotlin Multiplatform in Practise
Coroutines for Kotlin Multiplatform in PractiseChristian Melchior
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing UpDavid Padbury
 
Ruby Xml Mapping
Ruby Xml MappingRuby Xml Mapping
Ruby Xml MappingMarc Seeger
 
Blocks & GCD
Blocks & GCDBlocks & GCD
Blocks & GCDrsebbe
 
Master in javascript
Master in javascriptMaster in javascript
Master in javascriptRobbin Zhao
 

Similar a Moose (20)

Moose: Perl Objects
Moose: Perl ObjectsMoose: Perl Objects
Moose: Perl Objects
 
Lombok Features
Lombok FeaturesLombok Features
Lombok Features
 
Introduction to Ecmascript - ES6
Introduction to Ecmascript - ES6Introduction to Ecmascript - ES6
Introduction to Ecmascript - ES6
 
Clojure for Java developers
Clojure for Java developersClojure for Java developers
Clojure for Java developers
 
JRuby e DSL
JRuby e DSLJRuby e DSL
JRuby e DSL
 
Introduction to clojure
Introduction to clojureIntroduction to clojure
Introduction to clojure
 
JavaScript Miller Columns
JavaScript Miller ColumnsJavaScript Miller Columns
JavaScript Miller Columns
 
A tour on ruby and friends
A tour on ruby and friendsA tour on ruby and friends
A tour on ruby and friends
 
TorqueBox: The beauty of Ruby with the power of JBoss. Presented at Devnexus...
TorqueBox: The beauty of Ruby with the power of JBoss.  Presented at Devnexus...TorqueBox: The beauty of Ruby with the power of JBoss.  Presented at Devnexus...
TorqueBox: The beauty of Ruby with the power of JBoss. Presented at Devnexus...
 
Macruby - RubyConf Presentation 2010
Macruby - RubyConf Presentation 2010Macruby - RubyConf Presentation 2010
Macruby - RubyConf Presentation 2010
 
Future Programming Language
Future Programming LanguageFuture Programming Language
Future Programming Language
 
Real world cross-platform testing
Real world cross-platform testingReal world cross-platform testing
Real world cross-platform testing
 
Groovy Metaprogramming for Dummies
Groovy Metaprogramming for DummiesGroovy Metaprogramming for Dummies
Groovy Metaprogramming for Dummies
 
55j7
55j755j7
55j7
 
Coroutines for Kotlin Multiplatform in Practise
Coroutines for Kotlin Multiplatform in PractiseCoroutines for Kotlin Multiplatform in Practise
Coroutines for Kotlin Multiplatform in Practise
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
Ruby Xml Mapping
Ruby Xml MappingRuby Xml Mapping
Ruby Xml Mapping
 
Blocks & GCD
Blocks & GCDBlocks & GCD
Blocks & GCD
 
Master in javascript
Master in javascriptMaster in javascript
Master in javascript
 
ES6 - JavaCro 2016
ES6 - JavaCro 2016ES6 - JavaCro 2016
ES6 - JavaCro 2016
 

Último

CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
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
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
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
 
"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
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
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
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 

Último (20)

CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
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
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
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.
 
"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
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
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
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 

Moose

  • 1. What is Moose? man Moose: “A postmodern object system for perl 5.” Inspired by Metaobject Protocol of Common Lisp Object System (CLOS) A partial backport of Perl 6 concepts to Perl 5 Makes module definition trivial Has constraints for checking args to constructors, getters, setters Has roles (called ’traits’ in the programming languages literature) (A few slides on Test::MockObject at end of talk.) Nicholas Dronen () Moose, XML::LibXML, and Test::MockObject November 10, 2009 1 / 15
  • 2. Defining a constructor: This is your module package ModuleWithoutMoose; sub new { my $proto = shift; my $class = ref($proto) || $proto; my $self = bless({}, $class); my %args = @_; # Validate $args{foo} $self->{foo} = $args{foo}; # Validate $args{bar}; $self->{bar} = $args{bar}; return $self; } 1; Nicholas Dronen () Moose, XML::LibXML, and Test::MockObject November 10, 2009 2 / 15
  • 3. Defining a constructor: This is your module on Moose package ModuleWithMoose; use Moose; has ’foo’ => (is => ’ro’, isa => ’Str’, required => 1); has ’bar’ => (is => ’rw’, isa => ’Num’, required => 1); no Moose; __PACKAGE__->meta->make_immutable; 1; Nicholas Dronen () Moose, XML::LibXML, and Test::MockObject November 10, 2009 3 / 15
  • 4. What does that do? has creates an attribute (field (Java), member var (C++)) has creates a getter/setter with same name as the attribute is declares the attribute read-only or read-write required = 1 means an exception is thrown if arg is not present no Moose, make immutable reseal the module (faster) Nicholas Dronen () Moose, XML::LibXML, and Test::MockObject November 10, 2009 4 / 15
  • 5. Using a Moose module (constructor) use ModuleWithMoose; # OK ModuleWithMoose->new(foo => "hello", bar => 2); # Dies: type of ’bar’ ModuleWithMoose->new(foo => "hello", bar => "bad"); # Dies: ’bar’ required ModuleWithMoose->new(foo => "hello"); Nicholas Dronen () Moose, XML::LibXML, and Test::MockObject November 10, 2009 5 / 15
  • 6. Using a Moose module (getter/setter) use ModuleWithMoose; my $o = ModuleWithMoose->new(foo => "hello", bar => 2); # Prints "hello" print $o->foo(); # Dies: ’foo’ is red-only $o->foo("bad"); # OK: ’bar’ is writable $o->bar(10); # Dies: type of ’bar’ $o->bar("bad"); Nicholas Dronen () Moose, XML::LibXML, and Test::MockObject November 10, 2009 6 / 15
  • 7. Attribute initialization No guarantee on order of initialization This is a problem when one attribute depends on another Solution is to use lazy or lazy build Simple attributes (scalars or empty refs): default is ok Complex attributes (all others): use builder instead builder => NAME , where NAME is a method Builder method conventionally named build ATTRNAME Nicholas Dronen () Moose, XML::LibXML, and Test::MockObject November 10, 2009 7 / 15
  • 8. Type constraints isa => ’Str’ a string (undef illegal) isa => ’Maybe[Str]’ a string (undef legal) isa => ’ArrayRef[Num]’ an array ref of numbers isa => ’ArrayRef[Maybe[Str]]’ an array ref of strings (undef legal) isa => ’XML::LibXML::Element’ an instance of stated kind perldoc Moose::Util::TypeConstraints and perldoc Moose::Manual::Types Nicholas Dronen () Moose, XML::LibXML, and Test::MockObject November 10, 2009 8 / 15
  • 9. Validation of arguments to other methods Use Moose type constraints to validate args to arbitrary methods See MooseX::Params::Validate (not 5.8.2 or 5.10.1 PKT-perl) Also see MooseX::Method::Signatures (not in 5.8.2 or 5.10.1 PKT-perl) method morning (Str $name) { $self->say("Good morning ${name}!"); } Nicholas Dronen () Moose, XML::LibXML, and Test::MockObject November 10, 2009 9 / 15
  • 10. Roles A role is like an abstract base class, but not a class A role is like an interface, but contains code Like a mixin in the classical LISP-ian sense, but not in the inheritance hierarchy Ruby’s mixins are similar Inspired by traits Larry Wall (Perl 6 objects spec): “Classes are primarily for instance management, not code reuse.” Nicholas Dronen () Moose, XML::LibXML, and Test::MockObject November 10, 2009 10 / 15
  • 11. Traits Traits: Composable Units of Behavior, ECOOP’2003, LNCS 2743, pp. 248-274, Springer Verlag, 2003 “A class has a primary role as a generator of instances.” Not ideal for code reuse. Single inheritance not flexible enough Multiple inheritance has problems (diamond problem, upreferences) Interfaces don’t help code reuse; need either multiple implementations or a helper class in some cases (Classical) mixins are part of single inheritance hierarchy; can’t access overridden methods Traits have flattening property, are not part of any inheritance hierarchy Traits make demands of classes (or traits) that use them Conflicts in names of traits resolved via aliases Nicholas Dronen () Moose, XML::LibXML, and Test::MockObject November 10, 2009 11 / 15
  • 12. Defining a role package Expirable; use Moose::Role; # Demand that our consumer have ’handle’ and ’name’ method requires qw(handle name); sub handleWithTimeout { my $self = shift; # Initialize local variables try { local $SIG{ALRM} = sub { confess }; alarm($seconds); $self->handle(%args); alarm(0); } catch { # Handle exception }; } no Moose::Role; 1; Nicholas Dronen () Moose, XML::LibXML, and Test::MockObject November 10, 2009 12 / 15
  • 13. Consuming a role package ModuleThatCanExpire; use Moose; # If I have ’handle’ and ’name’ methods, this succeeds, # and it gives me a ’handleWithTimeout’ method. with ’Expirable’; Nicholas Dronen () Moose, XML::LibXML, and Test::MockObject November 10, 2009 13 / 15
  • 14. Gotchas: Exceptions Error module incompatible with Moose Both modules export a function named ’with’ Options Try::Tiny Simple implementation Already in 5.8.2 and 5.10.1 PKT-perl TryCatch Nicer semantics Can return from a block Adds hooks to the compiler to do the right thing Not in 5.8.2 or 5.10.1 PKT-perl; would be nice for 5.10.1 Nicholas Dronen () Moose, XML::LibXML, and Test::MockObject November 10, 2009 14 / 15
  • 15. Test::MockObject Unit test: test your code in isolation from all other code Problem: references to concrete types (e.g. Foo->new()). To attain testability in Java: interfaces, factories, dependency injection Then use a mock object library (e.g. EasyMock, jMock, others) Not so in Perl! Test::MockObject allows you to mock out the loader Akin to mocking out an import in Java Now Foo->new() doesn’t impede unit-testability Good for testing legacy code Duck typing is nice, but Foo->new() and use Foo are the only textual signals you have that you’re actually using a Foo. Not in 5.8.2 PKT-perl; in 5.10.1 PKT-perl Nicholas Dronen () Moose, XML::LibXML, and Test::MockObject November 10, 2009 15 / 15