SlideShare ist ein Scribd-Unternehmen logo
1 von 45
When “is a” and “has a”
    wouldn’t do!
Traits composition
Who?
         Marielle Lange @widged

 Flex developer for    Academic
 a living (since       background (last at
 2008)                 “The Institute for
                       Adaptive and
 Javascript & jQuery
                       Neural
Traits?
  •   Clearly separates issues of instance generation
      and units of reuse
  •   Composition mechanisms
      •   Divorced from the inheritance hierarchy ➡
          Avoid difficulties experienced with multiple
          inheritance.
      •   Impose no composition order ➡ Avoid
          difficulties experienced with mixins.

  •   Introduced in SmallTalk. Particularly suited to
      class-less languages like Javascript. Also found in
      class-based ones. Recently added to PHP.
      Supported in Scala (Java)
Focuses on Rules


Input                   Output
                Rules

        State
Object-Oriented
Spirit of the law (here
OO language) vs letter
       of the law
Object Oriented


   An 'Objects and classes' approach
   allows for the design of components
   that are fully re-usable across
   projects and sometimes across
   programming frameworks.
Objects
 Reference to objects that are meant to
 mimic real world behaviour.
  • Intuitive and consistent abstractions of
    the problem being solved throughout
    the analysis, design, implementation,
    and maintenance phases of
    development.

  • Provision for testing and the ability to
    embrace change.
Classes       (Templates for objects)

 • Conflicting purposes
  • As generators of objects, classes must be
    complete and monolithic.
  • As units of reuse via inheritance, they
    should be small, fine-grained, and possibly
    incomplete.


  James Gosling, creator of Java, once said
  that if he could do Java over again, he
Fragile inheritance chains

Is a Bird
            lacks flying
Has wings                 code
            ➡ flightless   duplication
            bird
                          is a FLBTCS?

            ➡ flightless   has a swim
                          manager?
Has buoyant bird,
body        implements
            swimmer
Multiple inheritance

     Bird   Swimmer    Flyer
Traits composition



  Bird                           BirdMan
     can swim       Bird           can swim
     (swim trait)                  can fly
                      can swim
                      can fly

  Traits are coherent collections of methods
  that can be reused anywhere in the
Re-use, no
  • Halfway between an interface and a class.
    • Like interfaces, they define behaviors that
      the objects can implement. Unlike
      interfaces, the definition includes the actual
      implementation.
    • Like classes, they provide method
      implementations that can be acquired by
      objects. However, they are stateless (they
      don’t include instance variables), not bound to
      a hierarchy (inheritance chain) and do not have
      to be complete (they do not have to define all
Languages limitations
  • Straightforward to implement in languages
    like javascript that treat functions as first
    class objects.
   • var a = function() {}   ➡  Functions can be
      passed as arguments to other functions,
      returning them as the values from other
      functions, and assigning them to variables
      or storing them in data structures.

  • Require language modifications or
    preprocessing solutions for languages that
Traits 101
Set of methods



  • A trait includes:
   • Only methods
   • No state (no instance variable)
Example

 <?php
 trait HelloWorld {
     public function sayHello() {
         echo 'Hello World!';
     }
 }

 class Greeter {
     use HelloWorld;
 }

 $o = new Greeter();
 $o->sayHello(); // =>'Hello World!'
 ?>




 Adapted from: http://php.net/manual/en/language.oop5.traits.php
Composition Rules

  1. When a class uses a trait, the
     behaviour provided by the trait gets
     incorporated (flattened) into the
     class. This means that the
     semantics is basically the same as if
     the services (methods) provided by
     the trait were implemented in the
     class itself.
Example
 trait HelloWorld {
     public function sayHello() {                   Different
                                                    from a
         echo 'Hello World!';
     }
 }

 class UniverseGreeter {
                                                    delegate in
     public function sayHelloUniverse() {
         echo 'Hello Universe!';                    the decorator
     }
 }                                                  pattern
 class Greeter {
     use HelloWorld;
     $universeDelegate = new UniverseGreeter();
     public function sayHelloUniverse() {  
         echo $universeDelegate->sayHello();
     }
 }

 $o = new Greeter();
 $o->sayHello();           // =>'Hello World!'
 $o->sayHelloUniverse();   // =>'Hello Universe!'


 Adapted from: http://php.net/manual/en/language.oop5.traits.php
Composition Rules (ctnd)


  2. Methods defined in a class take
     precedence over methods provided
     by a trait (any trait method can be
     overridden by a method with the
     same name).
Example                                  Class

 <?php
 trait HelloWorld {
     public function sayHello() {
         echo 'Hello World!';
     }
 }

 class TheWorldIsNotEnough {
     use HelloWorld;
     public function sayHello() {
         echo 'Hello Universe!';
     }
 }

 $o = new TheWorldIsNotEnough();
 $o->sayHello(); // Hello Universe!
 ?>




     source: http://php.net/manual/en/language.oop5.traits.php
Composition Rules (ctnd)


  3. Composition order is irrelevant. All
     the traits have the same
     precedence, and hence conflicting
     trait methods must be explicitly
     disambiguated.
Example                             Conflict

 <?php
 trait A {                           class Talker {
     public function smallTalk()         use A, B {
 {                                           B::smallTalk insteadof A;
         echo 'a';                           A::bigTalk insteadof B;
     }                                   }
     public function bigTalk() {     }
         echo 'A';
     }                               class Aliased_Talker {
 }                                       use A, B {
                                             B::smallTalk insteadof A;
 trait B {                                   A::bigTalk insteadof B;
     public function smallTalk()             B::bigTalk as talk;
 {                                       }
                                     }
         echo 'b';                   The composer has full
     }
     public function bigTalk() {     control over the
                                     ?>
         echo 'B';
     }                               composition
 }
                                    Sum, override, exclusion,
                                    aliasing.
     Source: http://php.net/manual/en/language.oop5.traits.php
Incompleteness
  • Traits don’t have to be complete
   • Traits can require methods used by,
      but not implemented in, a trait.

  • It is the class responsibility to provide
    an implementation for every service
    required by any of the used traits
    (glue code in the class itself, in a
    direct or indirect super-class, or in
    another trait that is used by the class).
Example                                      Requires


  <?php

                                                Traits can
  trait Hello {
      public function sayHelloWorld() {
          echo 'Hello'.$this->getWorld();
      }
      abstract public function getWorld();
                                                access state
  }
                                                indirectly,
  class MyHelloWorld {
      private $world;                           through
      use Hello;
      public function getWorld() {
          return $this->world;
                                                required
      }
      public function setWorld($val) {
                                                accessor
          $this->world = $val;
      }                                         services.
  }
  ?>




      source: http://php.net/manual/en/language.oop5.traits.php
Composite traits


  • Traits cannot define a superclass.
  • However, in some languages, it is
    possible to define composite traits.
    That is, traits that are composed of
    other traits.
Traits for
enterprise
Language support


  Supported in Smalltalk, PHP, Scala
  (Java), C#, JavaScript
Objects with traits

   • Intuitive and consistent        ✓
     abstractions of the problem
     being solved throughout the
     analysis, design,
     implementation, and
     maintenance phases of
     development.                    ✓
   • Provision for testing and the
Duplication of code
  • In languages that don’t treat functions as first
    class objects, traits are typically flattened into
    a class by compiler assisted copy and paste.
    • Duplication of code to avoid runtime
       overhead.

  • In essence, stateless traits are incomplete. They
    necessarily encode dependency on state in
    terms of required accessors methods (getters,
    setters) that the composing class must define ➡
    Each client class has to implement boilerplate
    glue code.
Tight coupling to
  • A trait solution tightly couples the trait
    implementation to the using class.
    This can actually reduce the
    reusability and utility of the class
    itself.
  • These are problems that we normally
    use design patterns to solve (such as
    Decorator, Composite and Bridge). ➡
    Encourages a quick solution were
    refactoring should be considered.

            (source: Traits are the new Eval)
Fragile to change
  • Fragile to incremental or unanticipated
    change

    • Changing the signature of a trait method
      will impact all the clients that use the
      method.

    • Adding or deleting methods provided by a
      trait may well impact clients by introducing
      new conflicts or requirements.

    • Adding new state requirement in a trait will
      demand new accessors in all client classes.

               (source: Stateful traits, PDF)
Accessors break encapsulation

   • Traits tend to unnecessarily expose information.
   • Traits methods used in client-classes must be
      public.

   • A client class using a trait get to see all
      methods, and not just the ones that are truly its
      responsibility to implement.

   • The glue code in the class, must be public. If
      traits require accessors to access state (i.e.,
      instance variables), then classes using these
      traits must provide public accessors to the
      missing state.
Initialization

   • Since traits cannot contain state,
     variables cannot be declared directly
     in the trait. Accessors for that variable
     are made required methods instead.
   • Where should variables be initialized?
    • In the class using the trait?
    • In the trait and pushed into the
       class via a required setter?
Trait modification
       • In dynamical languages, like
           JavaScript, potential for the trait to be
           modified after it has been imported.

Core.clone = function(obj) {
                                           If you compose a
	 return ns.Core.extend({}, obj);
}
                                           trait into your class,
Core.extend = function(obj, added) {
	 for (key in added) {
                                           then add a method
        if (added.hasOwnProperty(key)) {
            obj[key] = added[key];
                                           to the trait at run
    }
        }
                                           time, the method will
	 return obj;
}
                                           not be available to
                                           your class.
New Tools Required
Horizontal

  • Representations of single
    inheritance class hierarchies are
    working well in IDEs.

  • Traits offer a new orthogonal
    relation between classes and traits.

   • The addition of breadth makes it
     harder to represent and
     understand.

           (source: Traits are the new Eval)
Composition Explorer
  • Keeping track of the dependencies
    between traits and classes.

   • How the responsibilities of a class are
      decomposed into several traits and how
      these traits are glued together in order
      to achieve the required behaviour.

   • How the class meets the requirements
      of its component traits: the provided
      and required methods, the overridden
      methods, and the glue methods.

     (source: Traits: Composable Units of Behaviour*, PDF)
Edit time warnings
  • If a modification causes a new
    conflict or an unspecified
    requirement anywhere in the
    system, the affected classes and
    traits are automatically added to a
    “to do” list.

  • The tools should announce a
    conflict if a method of the same
    name and signature is obtained
     (source: Traits: Composable Units of Behaviour*, PDF)
Glue code generation
    • Generation of required methods that
        correspond to instance variable accessors.

       • preferably avoiding actual duplication.
    • Semi-automated solutions to conflict
        resolution.

       • List of alternative implementations
       • Choosing one generates the
           composition clause that excludes the
           others, and thus eliminates the conflict.

 (source: “ Traits: Composable Units of Behaviour* “ and “Stateful Traits “)
Debugging


  • Traits should be represented in the
    debugger, so that a programmer
    can easily map code being executed
    to the actual source code (written
    with traits).



   (source: Adding Traits to (Statically Typed) Languages, PDF)
Runtime reflection
  • Many programming languages allow to
    reflect and sometimes even manipulate
    the program being executed.

  • It is important that traits are correctly
    represented in the reflective
    infrastructure of the language, so that
    one can for example ask which
    methods are provided by a certain trait
    or which traits are used by a certain
    class.
    (source: Adding Traits to (Statically Typed) Languages, PDF)
Thoughts?
“can do”
  • Thinking in terms of what an
    instance “can do”, in addition to the
    familiar “is a”and “has a” modes of
    composition.

  • Keeping in mind that you don’t
    necessarily have to encapsulate
    variables and methods in a class.
Functional Pg
Look at    Function.prototype.partial = function(){
             var fn   = this,
Partials         args = Array.prototype.slice.call(arguments);
             return function(){
               var arg = 0;
               for ( var i = 0; i < args.length &&
                                arg < arguments.length; i++ )
                 if ( args[i] === undefined )
                   args[i] = arguments[arg++];
               return fn.apply(this, args);
             };
           };
            
           String.prototype.csv2 =
                      String.prototype.split.partial(/,s*/);
           ("John, Resig, Boston").csv2() => ["Resig"] 
Thanks!

@widged

Weitere ähnliche Inhalte

Was ist angesagt?

Clojure - An Introduction for Lisp Programmers
Clojure - An Introduction for Lisp ProgrammersClojure - An Introduction for Lisp Programmers
Clojure - An Introduction for Lisp Programmerselliando dias
 
Java essentials for hadoop
Java essentials for hadoopJava essentials for hadoop
Java essentials for hadoopSeo Gyansha
 
Moose Meta-Modeling Infrastructure
Moose Meta-Modeling InfrastructureMoose Meta-Modeling Infrastructure
Moose Meta-Modeling InfrastructureESUG
 
Clojure and The Robot Apocalypse
Clojure and The Robot ApocalypseClojure and The Robot Apocalypse
Clojure and The Robot Apocalypseelliando dias
 
Java 8 selected updates
Java 8 selected updatesJava 8 selected updates
Java 8 selected updatesVinay H G
 
Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8Talha Ocakçı
 
Functional Java 8 - Introduction
Functional Java 8 - IntroductionFunctional Java 8 - Introduction
Functional Java 8 - IntroductionŁukasz Biały
 
Irving iOS Jumpstart Meetup - Objective-C Session 1b
Irving iOS Jumpstart Meetup - Objective-C Session 1bIrving iOS Jumpstart Meetup - Objective-C Session 1b
Irving iOS Jumpstart Meetup - Objective-C Session 1birving-ios-jumpstart
 
Programming Paradigms
Programming ParadigmsProgramming Paradigms
Programming ParadigmsDirecti Group
 
Intro to java 8
Intro to java 8Intro to java 8
Intro to java 8John Godoi
 

Was ist angesagt? (17)

Clojure - An Introduction for Lisp Programmers
Clojure - An Introduction for Lisp ProgrammersClojure - An Introduction for Lisp Programmers
Clojure - An Introduction for Lisp Programmers
 
Java essentials for hadoop
Java essentials for hadoopJava essentials for hadoop
Java essentials for hadoop
 
pebble - Building apps on pebble
pebble - Building apps on pebblepebble - Building apps on pebble
pebble - Building apps on pebble
 
Kotlin Types for Java Developers
Kotlin Types for Java DevelopersKotlin Types for Java Developers
Kotlin Types for Java Developers
 
Java beans
Java beansJava beans
Java beans
 
Intro to Scala
 Intro to Scala Intro to Scala
Intro to Scala
 
Moose Meta-Modeling Infrastructure
Moose Meta-Modeling InfrastructureMoose Meta-Modeling Infrastructure
Moose Meta-Modeling Infrastructure
 
Clojure and The Robot Apocalypse
Clojure and The Robot ApocalypseClojure and The Robot Apocalypse
Clojure and The Robot Apocalypse
 
Java 8 selected updates
Java 8 selected updatesJava 8 selected updates
Java 8 selected updates
 
Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8
 
Java script
Java scriptJava script
Java script
 
Functional Java 8 - Introduction
Functional Java 8 - IntroductionFunctional Java 8 - Introduction
Functional Java 8 - Introduction
 
Groovy Programming Language
Groovy Programming LanguageGroovy Programming Language
Groovy Programming Language
 
Irving iOS Jumpstart Meetup - Objective-C Session 1b
Irving iOS Jumpstart Meetup - Objective-C Session 1bIrving iOS Jumpstart Meetup - Objective-C Session 1b
Irving iOS Jumpstart Meetup - Objective-C Session 1b
 
Code generating beans in Java
Code generating beans in JavaCode generating beans in Java
Code generating beans in Java
 
Programming Paradigms
Programming ParadigmsProgramming Paradigms
Programming Paradigms
 
Intro to java 8
Intro to java 8Intro to java 8
Intro to java 8
 

Andere mochten auch

Standarized tools
Standarized toolsStandarized tools
Standarized toolsManu Sethi
 
Personality and Measurement
Personality and MeasurementPersonality and Measurement
Personality and MeasurementSeta Wicaksana
 
personality, theory and measurement
personality, theory and measurementpersonality, theory and measurement
personality, theory and measurementSeta Wicaksana
 
Organizational Behavior Chapter 4 Personality and Values
Organizational Behavior Chapter 4 Personality and ValuesOrganizational Behavior Chapter 4 Personality and Values
Organizational Behavior Chapter 4 Personality and ValuesDr. John V. Padua
 
Measuring personality
Measuring personalityMeasuring personality
Measuring personalityStudying
 
Allport’s trait theory of personality
Allport’s trait theory of personalityAllport’s trait theory of personality
Allport’s trait theory of personalityEnu Sambyal
 

Andere mochten auch (9)

Standarized tools
Standarized toolsStandarized tools
Standarized tools
 
Traits slide,5.12.2012
Traits slide,5.12.2012Traits slide,5.12.2012
Traits slide,5.12.2012
 
Personality and Measurement
Personality and MeasurementPersonality and Measurement
Personality and Measurement
 
Trait theory.report
Trait theory.reportTrait theory.report
Trait theory.report
 
personality, theory and measurement
personality, theory and measurementpersonality, theory and measurement
personality, theory and measurement
 
Organizational Behavior Chapter 4 Personality and Values
Organizational Behavior Chapter 4 Personality and ValuesOrganizational Behavior Chapter 4 Personality and Values
Organizational Behavior Chapter 4 Personality and Values
 
Measuring personality
Measuring personalityMeasuring personality
Measuring personality
 
Trait approach
Trait approachTrait approach
Trait approach
 
Allport’s trait theory of personality
Allport’s trait theory of personalityAllport’s trait theory of personality
Allport’s trait theory of personality
 

Ähnlich wie Traits composition

Take the Plunge with OOP from #pnwphp
Take the Plunge with OOP from #pnwphpTake the Plunge with OOP from #pnwphp
Take the Plunge with OOP from #pnwphpAlena Holligan
 
Object-oriented Design: Polymorphism via Inheritance (vs. Delegation)
Object-oriented Design: Polymorphism via Inheritance (vs. Delegation)Object-oriented Design: Polymorphism via Inheritance (vs. Delegation)
Object-oriented Design: Polymorphism via Inheritance (vs. Delegation)Adair Dingle
 
Lecture-10_PHP-OOP.pptx
Lecture-10_PHP-OOP.pptxLecture-10_PHP-OOP.pptx
Lecture-10_PHP-OOP.pptxShaownRoy1
 
Intro to OOP PHP and Github
Intro to OOP PHP and GithubIntro to OOP PHP and Github
Intro to OOP PHP and GithubJo Erik San Jose
 
Md02 - Getting Started part-2
Md02 - Getting Started part-2Md02 - Getting Started part-2
Md02 - Getting Started part-2Rakesh Madugula
 
INDUMATHY- UNIT 1 cs3391 oops introduction to oop and java.pptx
INDUMATHY- UNIT 1 cs3391 oops introduction to oop and java.pptxINDUMATHY- UNIT 1 cs3391 oops introduction to oop and java.pptx
INDUMATHY- UNIT 1 cs3391 oops introduction to oop and java.pptxIndu65
 
Function-and-prototype defined classes in JavaScript
Function-and-prototype defined classes in JavaScriptFunction-and-prototype defined classes in JavaScript
Function-and-prototype defined classes in JavaScriptHong Langford
 
Owner - Java properties reinvented.
Owner - Java properties reinvented.Owner - Java properties reinvented.
Owner - Java properties reinvented.Luigi Viggiano
 
DSL's with Groovy
DSL's with GroovyDSL's with Groovy
DSL's with Groovypaulbowler
 
Java Basics for selenium
Java Basics for seleniumJava Basics for selenium
Java Basics for seleniumapoorvams
 
Java Basics Presentation
Java Basics PresentationJava Basics Presentation
Java Basics PresentationOmid Sohrabi
 
full defination of final opp.pptx
full defination of final opp.pptxfull defination of final opp.pptx
full defination of final opp.pptxrayanbabur
 
Traits: A New Language Feature for PHP?
Traits: A New Language Feature for PHP?Traits: A New Language Feature for PHP?
Traits: A New Language Feature for PHP?Stefan Marr
 
ITT 202 PRINCIPLES OF OBJECT ORIENTED TECHNIQUE
ITT 202 PRINCIPLES OF OBJECT ORIENTED TECHNIQUEITT 202 PRINCIPLES OF OBJECT ORIENTED TECHNIQUE
ITT 202 PRINCIPLES OF OBJECT ORIENTED TECHNIQUEVinishA23
 
Java Closures
Java ClosuresJava Closures
Java ClosuresBen Evans
 
Android Training (Java Review)
Android Training (Java Review)Android Training (Java Review)
Android Training (Java Review)Khaled Anaqwa
 

Ähnlich wie Traits composition (20)

Andy On Closures
Andy On ClosuresAndy On Closures
Andy On Closures
 
Take the Plunge with OOP from #pnwphp
Take the Plunge with OOP from #pnwphpTake the Plunge with OOP from #pnwphp
Take the Plunge with OOP from #pnwphp
 
Object-oriented Design: Polymorphism via Inheritance (vs. Delegation)
Object-oriented Design: Polymorphism via Inheritance (vs. Delegation)Object-oriented Design: Polymorphism via Inheritance (vs. Delegation)
Object-oriented Design: Polymorphism via Inheritance (vs. Delegation)
 
Lecture-10_PHP-OOP.pptx
Lecture-10_PHP-OOP.pptxLecture-10_PHP-OOP.pptx
Lecture-10_PHP-OOP.pptx
 
Intro to OOP PHP and Github
Intro to OOP PHP and GithubIntro to OOP PHP and Github
Intro to OOP PHP and Github
 
PHP 5
PHP 5PHP 5
PHP 5
 
Md02 - Getting Started part-2
Md02 - Getting Started part-2Md02 - Getting Started part-2
Md02 - Getting Started part-2
 
INDUMATHY- UNIT 1 cs3391 oops introduction to oop and java.pptx
INDUMATHY- UNIT 1 cs3391 oops introduction to oop and java.pptxINDUMATHY- UNIT 1 cs3391 oops introduction to oop and java.pptx
INDUMATHY- UNIT 1 cs3391 oops introduction to oop and java.pptx
 
Function-and-prototype defined classes in JavaScript
Function-and-prototype defined classes in JavaScriptFunction-and-prototype defined classes in JavaScript
Function-and-prototype defined classes in JavaScript
 
Owner - Java properties reinvented.
Owner - Java properties reinvented.Owner - Java properties reinvented.
Owner - Java properties reinvented.
 
Only oop
Only oopOnly oop
Only oop
 
The smartpath information systems java
The smartpath information systems javaThe smartpath information systems java
The smartpath information systems java
 
DSL's with Groovy
DSL's with GroovyDSL's with Groovy
DSL's with Groovy
 
Java Basics for selenium
Java Basics for seleniumJava Basics for selenium
Java Basics for selenium
 
Java Basics Presentation
Java Basics PresentationJava Basics Presentation
Java Basics Presentation
 
full defination of final opp.pptx
full defination of final opp.pptxfull defination of final opp.pptx
full defination of final opp.pptx
 
Traits: A New Language Feature for PHP?
Traits: A New Language Feature for PHP?Traits: A New Language Feature for PHP?
Traits: A New Language Feature for PHP?
 
ITT 202 PRINCIPLES OF OBJECT ORIENTED TECHNIQUE
ITT 202 PRINCIPLES OF OBJECT ORIENTED TECHNIQUEITT 202 PRINCIPLES OF OBJECT ORIENTED TECHNIQUE
ITT 202 PRINCIPLES OF OBJECT ORIENTED TECHNIQUE
 
Java Closures
Java ClosuresJava Closures
Java Closures
 
Android Training (Java Review)
Android Training (Java Review)Android Training (Java Review)
Android Training (Java Review)
 

Kürzlich hochgeladen

Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
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
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
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
 
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
 
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
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
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
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
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
 

Kürzlich hochgeladen (20)

Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
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
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
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
 
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
 
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
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
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
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
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
 

Traits composition

  • 1. When “is a” and “has a” wouldn’t do! Traits composition
  • 2. Who? Marielle Lange @widged Flex developer for Academic a living (since background (last at 2008) “The Institute for Adaptive and Javascript & jQuery Neural
  • 3. Traits? • Clearly separates issues of instance generation and units of reuse • Composition mechanisms • Divorced from the inheritance hierarchy ➡ Avoid difficulties experienced with multiple inheritance. • Impose no composition order ➡ Avoid difficulties experienced with mixins. • Introduced in SmallTalk. Particularly suited to class-less languages like Javascript. Also found in class-based ones. Recently added to PHP. Supported in Scala (Java)
  • 4. Focuses on Rules Input Output Rules State
  • 5. Object-Oriented Spirit of the law (here OO language) vs letter of the law
  • 6. Object Oriented An 'Objects and classes' approach allows for the design of components that are fully re-usable across projects and sometimes across programming frameworks.
  • 7. Objects Reference to objects that are meant to mimic real world behaviour. • Intuitive and consistent abstractions of the problem being solved throughout the analysis, design, implementation, and maintenance phases of development. • Provision for testing and the ability to embrace change.
  • 8. Classes (Templates for objects) • Conflicting purposes • As generators of objects, classes must be complete and monolithic. • As units of reuse via inheritance, they should be small, fine-grained, and possibly incomplete. James Gosling, creator of Java, once said that if he could do Java over again, he
  • 9. Fragile inheritance chains Is a Bird lacks flying Has wings code ➡ flightless duplication bird is a FLBTCS? ➡ flightless has a swim manager? Has buoyant bird, body implements swimmer
  • 10. Multiple inheritance Bird Swimmer Flyer
  • 11. Traits composition Bird BirdMan can swim Bird can swim (swim trait) can fly can swim can fly Traits are coherent collections of methods that can be reused anywhere in the
  • 12. Re-use, no • Halfway between an interface and a class. • Like interfaces, they define behaviors that the objects can implement. Unlike interfaces, the definition includes the actual implementation. • Like classes, they provide method implementations that can be acquired by objects. However, they are stateless (they don’t include instance variables), not bound to a hierarchy (inheritance chain) and do not have to be complete (they do not have to define all
  • 13. Languages limitations • Straightforward to implement in languages like javascript that treat functions as first class objects. • var a = function() {} ➡ Functions can be passed as arguments to other functions, returning them as the values from other functions, and assigning them to variables or storing them in data structures. • Require language modifications or preprocessing solutions for languages that
  • 15. Set of methods • A trait includes: • Only methods • No state (no instance variable)
  • 16. Example <?php trait HelloWorld {     public function sayHello() {         echo 'Hello World!';     } } class Greeter {     use HelloWorld; } $o = new Greeter(); $o->sayHello(); // =>'Hello World!' ?> Adapted from: http://php.net/manual/en/language.oop5.traits.php
  • 17. Composition Rules 1. When a class uses a trait, the behaviour provided by the trait gets incorporated (flattened) into the class. This means that the semantics is basically the same as if the services (methods) provided by the trait were implemented in the class itself.
  • 18. Example trait HelloWorld {     public function sayHello() { Different from a         echo 'Hello World!';     } } class UniverseGreeter { delegate in     public function sayHelloUniverse() {         echo 'Hello Universe!'; the decorator     } } pattern class Greeter {     use HelloWorld;     $universeDelegate = new UniverseGreeter();     public function sayHelloUniverse() {           echo $universeDelegate->sayHello();     } } $o = new Greeter(); $o->sayHello(); // =>'Hello World!' $o->sayHelloUniverse(); // =>'Hello Universe!' Adapted from: http://php.net/manual/en/language.oop5.traits.php
  • 19. Composition Rules (ctnd) 2. Methods defined in a class take precedence over methods provided by a trait (any trait method can be overridden by a method with the same name).
  • 20. Example Class <?php trait HelloWorld {     public function sayHello() {         echo 'Hello World!';     } } class TheWorldIsNotEnough {     use HelloWorld;     public function sayHello() {         echo 'Hello Universe!';     } } $o = new TheWorldIsNotEnough(); $o->sayHello(); // Hello Universe! ?> source: http://php.net/manual/en/language.oop5.traits.php
  • 21. Composition Rules (ctnd) 3. Composition order is irrelevant. All the traits have the same precedence, and hence conflicting trait methods must be explicitly disambiguated.
  • 22. Example Conflict <?php trait A { class Talker {     public function smallTalk()      use A, B { {         B::smallTalk insteadof A;         echo 'a';         A::bigTalk insteadof B;     }     }     public function bigTalk() { }         echo 'A';     } class Aliased_Talker { }     use A, B {         B::smallTalk insteadof A; trait B {         A::bigTalk insteadof B;     public function smallTalk()          B::bigTalk as talk; {     } }         echo 'b'; The composer has full     }     public function bigTalk() { control over the ?>         echo 'B';     } composition } Sum, override, exclusion, aliasing. Source: http://php.net/manual/en/language.oop5.traits.php
  • 23. Incompleteness • Traits don’t have to be complete • Traits can require methods used by, but not implemented in, a trait. • It is the class responsibility to provide an implementation for every service required by any of the used traits (glue code in the class itself, in a direct or indirect super-class, or in another trait that is used by the class).
  • 24. Example Requires <?php Traits can trait Hello {     public function sayHelloWorld() {         echo 'Hello'.$this->getWorld();     }     abstract public function getWorld(); access state } indirectly, class MyHelloWorld {     private $world; through     use Hello;     public function getWorld() {         return $this->world; required     }     public function setWorld($val) { accessor         $this->world = $val;     } services. } ?> source: http://php.net/manual/en/language.oop5.traits.php
  • 25. Composite traits • Traits cannot define a superclass. • However, in some languages, it is possible to define composite traits. That is, traits that are composed of other traits.
  • 27. Language support Supported in Smalltalk, PHP, Scala (Java), C#, JavaScript
  • 28. Objects with traits • Intuitive and consistent ✓ abstractions of the problem being solved throughout the analysis, design, implementation, and maintenance phases of development. ✓ • Provision for testing and the
  • 29. Duplication of code • In languages that don’t treat functions as first class objects, traits are typically flattened into a class by compiler assisted copy and paste. • Duplication of code to avoid runtime overhead. • In essence, stateless traits are incomplete. They necessarily encode dependency on state in terms of required accessors methods (getters, setters) that the composing class must define ➡ Each client class has to implement boilerplate glue code.
  • 30. Tight coupling to • A trait solution tightly couples the trait implementation to the using class. This can actually reduce the reusability and utility of the class itself. • These are problems that we normally use design patterns to solve (such as Decorator, Composite and Bridge). ➡ Encourages a quick solution were refactoring should be considered. (source: Traits are the new Eval)
  • 31. Fragile to change • Fragile to incremental or unanticipated change • Changing the signature of a trait method will impact all the clients that use the method. • Adding or deleting methods provided by a trait may well impact clients by introducing new conflicts or requirements. • Adding new state requirement in a trait will demand new accessors in all client classes. (source: Stateful traits, PDF)
  • 32. Accessors break encapsulation • Traits tend to unnecessarily expose information. • Traits methods used in client-classes must be public. • A client class using a trait get to see all methods, and not just the ones that are truly its responsibility to implement. • The glue code in the class, must be public. If traits require accessors to access state (i.e., instance variables), then classes using these traits must provide public accessors to the missing state.
  • 33. Initialization • Since traits cannot contain state, variables cannot be declared directly in the trait. Accessors for that variable are made required methods instead. • Where should variables be initialized? • In the class using the trait? • In the trait and pushed into the class via a required setter?
  • 34. Trait modification • In dynamical languages, like JavaScript, potential for the trait to be modified after it has been imported. Core.clone = function(obj) { If you compose a return ns.Core.extend({}, obj); } trait into your class, Core.extend = function(obj, added) { for (key in added) { then add a method if (added.hasOwnProperty(key)) { obj[key] = added[key]; to the trait at run } } time, the method will return obj; } not be available to your class.
  • 36. Horizontal • Representations of single inheritance class hierarchies are working well in IDEs. • Traits offer a new orthogonal relation between classes and traits. • The addition of breadth makes it harder to represent and understand. (source: Traits are the new Eval)
  • 37. Composition Explorer • Keeping track of the dependencies between traits and classes. • How the responsibilities of a class are decomposed into several traits and how these traits are glued together in order to achieve the required behaviour. • How the class meets the requirements of its component traits: the provided and required methods, the overridden methods, and the glue methods. (source: Traits: Composable Units of Behaviour*, PDF)
  • 38. Edit time warnings • If a modification causes a new conflict or an unspecified requirement anywhere in the system, the affected classes and traits are automatically added to a “to do” list. • The tools should announce a conflict if a method of the same name and signature is obtained (source: Traits: Composable Units of Behaviour*, PDF)
  • 39. Glue code generation • Generation of required methods that correspond to instance variable accessors. • preferably avoiding actual duplication. • Semi-automated solutions to conflict resolution. • List of alternative implementations • Choosing one generates the composition clause that excludes the others, and thus eliminates the conflict. (source: “ Traits: Composable Units of Behaviour* “ and “Stateful Traits “)
  • 40. Debugging • Traits should be represented in the debugger, so that a programmer can easily map code being executed to the actual source code (written with traits). (source: Adding Traits to (Statically Typed) Languages, PDF)
  • 41. Runtime reflection • Many programming languages allow to reflect and sometimes even manipulate the program being executed. • It is important that traits are correctly represented in the reflective infrastructure of the language, so that one can for example ask which methods are provided by a certain trait or which traits are used by a certain class. (source: Adding Traits to (Statically Typed) Languages, PDF)
  • 43. “can do” • Thinking in terms of what an instance “can do”, in addition to the familiar “is a”and “has a” modes of composition. • Keeping in mind that you don’t necessarily have to encapsulate variables and methods in a class.
  • 44. Functional Pg Look at Function.prototype.partial = function(){   var fn   = this, Partials       args = Array.prototype.slice.call(arguments);   return function(){     var arg = 0;     for ( var i = 0; i < args.length &&            arg < arguments.length; i++ )       if ( args[i] === undefined )         args[i] = arguments[arg++];     return fn.apply(this, args);   }; };   String.prototype.csv2 = String.prototype.split.partial(/,s*/); ("John, Resig, Boston").csv2() => ["Resig"] 

Hinweis der Redaktion

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. \n
  38. \n
  39. \n
  40. \n
  41. \n
  42. \n
  43. \n
  44. \n
  45. \n