SlideShare a Scribd company logo
1 of 41
When Inheritance is not
enough. Mixins and others
ways to reuse code.
Maximiliano Fierro
@elmasse
Maximiliano Fierro
Sr. Solution Engineer
Co-Organizer
Sharing Code in OOP
ECMAScript is an Object
Oriented Programing Language
supporting delegating inheritance based on prototypes.
What does it mean?
Every Object references a
Prototype
[[Prototype]]: Internal property pointing to
the object prototype.
Some implementations provide the non-
standard __proto__ as explicit reference.
// Constructor
function MyClass (msg) {
this.msg = msg;
};
// Instance method
MyClass.prototype.foo = function ()
{
console.log(this.msg);
};
var a = new MyClass(‘Hello!’);
a.foo(); // Hello!
MyClass.prototype
foo()
[[Prototype]
]
msg
a
[[Prototype]
]
[[Prototype]
]
Object.prototype
null
...
// Constructor
function ClassA () {
// call parent constructor
MyClass.apply(this, arguments);
};
// inherit from MyClass
ClassA.prototype = Object.create(MyClass.prototype);
// Instance method
ClassA.prototype.bar = function () {
console.log(this.msg + ‘ from bar’);
};
var obj = new ClassA(‘Hello!’);
obj.foo(); // Hello!
obj.bar(); // Hello! from bar
MyClass.prototype
foo()
ClassA.prototype
bar()
[[Prototype]]
[[Prototype]]
msg
obj
“Using inheritance as a vehicle to
reuse code is a bit like ordering a
happy meal because you want the
plastic toy”
Angus Croll.
Abstract* / Base* Classes
When inheriting from a Framework / Library
Class (e.g. Views, Components, Controllers) and
you find common methods or repeated code in
several subclasses, often a Base Class is
created to “share” that common code.
Problems
Abstract/Base Classes
Deep hierarchy.
The Base/Abstract Class becomes a “bag of
common functions”.
Reusing Functions
Every (public) function can be invoked with .call
or .apply
It’s OK for simple functions...
var max = Math.max.apply(null, array);
… but code becomes wordy
var instance = {
msg: ‘Hello from instance’
};
//borrowing foo method from MyClass
MyClass.prototype.foo.apply(instance); // Hello from instance
//borrowing bar method from ClassA
ClassA.prototype.bar.apply(instance); // Hello from instance from bar
//borrowing foo method from ClassA inherited from MyClass
ClassA.prototype.foo.apply(instance); // Hello from instance
Mixins
Let’s share some code!
What is a Mixin?
A Mixin is a class that is, often, not intended to
be instantiated, but is combined into another
class.
Usually it is merged into a Class.
In JavaScript, we can use Objects as Mixins.
Mixins: Benefits
Encourage code reuse.
Can be seen as a workaround for
Multiple Inheritance.
Avoid the inheritance ambiguity (The
diamond problem) linearly.
Implementation
Using Object.assign (or polyfill)
- The Mixin is merged into the Class
prototype.
- Mixin can be Class or Object
function MixedClass () {
// call mixin constructor
MyClass.apply(this, arguments);
};
// apply Mixin
Object.assign(MixedClass.prototype,
MyClass.prototype);
// Instance method
MixedClass.prototype.bar = function () {
console.log(this.msg + ‘ from bar’);
};
var obj = new MixedClass(‘Hello!’);
obj.foo(); // Hello!
obj.bar(); // Hello! from bar
MixedClass.prototype
foo()
[[Prototype]
]
msg
obj
[[Prototype]
]
[[Prototype]
]
Object.prototype
null
...
bar()
EventEmitter as a Mixin
function MyClass() {
// call Mixin constructor
EventEmitter.call(this, arguments);
}
Object.assign(MyClass.prototype, EventEmitter.prototype);
var obj = new MyClass();
obj.on(‘event’, function ( ) { console.log(‘event!’); });
obj.emit(‘event’);
Functional Mixins
Mixin is not a class but a function that decorates the
prototype thru “this” keyword.
// Functional Mixin
function WithFoo() {
this.foo = function () {
console.log(this.msg);
}
return this;
}
// MixedClass definition
function MixedClass(msg) {
this.msg = msg;
}
// Apply Mixin
WithFoo.call(MixedClass.prototype);
MixedClass.prototype.bar = function () {
console.log(this.msg + ‘ from bar’);
};
var obj = new MixedClass(‘Hello!’);
obj.foo(); // Hello!
obj.bar(); // Hello! from bar
The Diamond Problem
BaseClass
ClassA ClassB
DerivedClass
foo()
var d = new DerivedClass();
d.foo() // which foo ??
...
...
...
foo()
The Diamond Problem cont’d
Object.assign(DerivedClass.prototype, ClassA.prototype, ClassB.prototype);
var d = new DerivedClass();
d.foo() // from ClassB
Object.assign(DerivedClass.prototype, ClassB.prototype, ClassA.prototype);
var d = new DerivedClass();
d.foo() // from ClassA
Calling an Overridden Method
….
Object.assign(DerivedClass.prototype, ClassA.prototype, ClassB.prototype);
DerivedClass.prototype.foo = function() {
// call “overridden” foo from A
ClassA.prototype.foo.apply(this, arguments);
}
Problems
Methods and properties are overridden based on
declaration position / implementation.
Refactoring (adding/renaming methods) can
cause “silent issues”.
Calling an overridden method is wordy and error
prone.
Traits
Sort of “Smart Mixins”
What is a Trait?
Composable Units of Behavior.
A special type of class with no state.
Can be seen as Incomplete classes.
Defines behavior and access state thru
required accessors.
Class = Traits + Glue Code + State
(+ SuperClass)
Composing Behavior
May require a set of methods to serve as
parameters for the provided behavior.
(Incomplete Classes)
Can be composed from other traits.
Name collision is solved by the Developer
(aliases or exclusions)
Conflict Resolution
Conflict arises when we combine two or more
traits providing identically named methods that
do not originate from the same trait.
Alias: A conflicting method can be “renamed”.
Exclusion: We can solve the conflict by just
excluding the method explicitly.
MyList.prototype
+getCollection()
[[Prototype]
]
withFirst <Trait>
first()
*getCollection()
withLast <Trait>
last()
*getCollection()
withIterator <Trait>
iterator()
*getCollection()
@traits
[[Prototype]
]
collection:
[1,2,3,4,5]
list
var list = new MyList([1,2,3,4,5]);
console.log('collection: ', list.getCollection());
// [1,2,3,4,5]
console.log('first: ', list.first()); // 1
console.log('last: ', list.last()); // 5
console.log('iterate:');
var iterator = list.iterator();
var value;
while(value = iterator.next()){
console.log(value);
}
(*) Required Method
(+) Glue Code
MyList.prototype
getCollection()
[[Prototype]
]
first()
last()
iterator()
[[Prototype]
]
collection:
[1,2,3,4,5]
list
MyList.prototype
getCollection():
{Array}
[[Prototype]
]
withFirst <Trait>
first()
*getCollection()
withLast <Trait>
last()
*getCollection()
withIterator <Trait>
iterator()
*getCollection()
@traits
[[Prototype]
]
collection:
[1,2,3,4,5]
list
var list = new MyList([1,2,3,4,5]);
console.log('collection: ',
list.getCollection());
// [1,2,3,4,5]
console.log('first: ', list.first()); // 1
console.log('last: ', list.last()); // 5
console.log('iterate:');
var iterator = list.iterator();
var value;
while(value = iterator.next()){
console.log(value);
}
iterable <Trait>
MyList.prototype
getCollection():
{Array}
[[Prototype]
]
withFirst <Trait>
first()
*getCollection()
withLast <Trait>
last()
*getCollection()
withIterator <Trait>
iterator()
*getCollection()
@traits
[[Prototype]
]
collection:
[1,2,3,4,5]
list
ERROR! method “first” is defined twice!
iterable <Trait>
first()
Conflict Resolution:
Alias or Exclude
we can exclude “first” from the iterable Trait or rename it in case
we want to use it.
Implementation
Libraries
• Traits.js
• CocktailJS
• (many others in npm)
CocktailJS
npm install -s cocktail
cocktailjs.github.io
Annotations. Traits & Talents
Demo
Thanks!
@elmasse
github.com/elmasse

More Related Content

What's hot

Seminar on java
Seminar on javaSeminar on java
Seminar on javashathika
 
Introduction to OOP with PHP
Introduction to OOP with PHPIntroduction to OOP with PHP
Introduction to OOP with PHPMichael Peacock
 
Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in javakamal kotecha
 
The Ruby Object Model by Rafael Magana
The Ruby Object Model by Rafael MaganaThe Ruby Object Model by Rafael Magana
The Ruby Object Model by Rafael MaganaRafael Magana
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteTushar B Kute
 
Object Oriented Programming in PHP
Object Oriented Programming in PHPObject Oriented Programming in PHP
Object Oriented Programming in PHPLorna Mitchell
 
encapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloadingencapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloadingShivam Singhal
 
Java oops PPT
Java oops PPTJava oops PPT
Java oops PPTkishu0005
 
Pi j3.2 polymorphism
Pi j3.2 polymorphismPi j3.2 polymorphism
Pi j3.2 polymorphismmcollison
 
PHP - Introduction to Object Oriented Programming with PHP
PHP -  Introduction to  Object Oriented Programming with PHPPHP -  Introduction to  Object Oriented Programming with PHP
PHP - Introduction to Object Oriented Programming with PHPVibrant Technologies & Computers
 

What's hot (20)

Ruby object model
Ruby object modelRuby object model
Ruby object model
 
Seminar on java
Seminar on javaSeminar on java
Seminar on java
 
Introduction to OOP with PHP
Introduction to OOP with PHPIntroduction to OOP with PHP
Introduction to OOP with PHP
 
Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in java
 
CLASS & OBJECT IN JAVA
CLASS & OBJECT  IN JAVACLASS & OBJECT  IN JAVA
CLASS & OBJECT IN JAVA
 
The Ruby Object Model by Rafael Magana
The Ruby Object Model by Rafael MaganaThe Ruby Object Model by Rafael Magana
The Ruby Object Model by Rafael Magana
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
 
Object Oriented Programming in PHP
Object Oriented Programming in PHPObject Oriented Programming in PHP
Object Oriented Programming in PHP
 
Only oop
Only oopOnly oop
Only oop
 
OOPs in Java
OOPs in JavaOOPs in Java
OOPs in Java
 
OOPS in Java
OOPS in JavaOOPS in Java
OOPS in Java
 
Generics in java
Generics in javaGenerics in java
Generics in java
 
Java(Polymorphism)
Java(Polymorphism)Java(Polymorphism)
Java(Polymorphism)
 
encapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloadingencapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloading
 
Java oops PPT
Java oops PPTJava oops PPT
Java oops PPT
 
Class introduction in java
Class introduction in javaClass introduction in java
Class introduction in java
 
Pi j3.2 polymorphism
Pi j3.2 polymorphismPi j3.2 polymorphism
Pi j3.2 polymorphism
 
Polymorphism in java
Polymorphism in javaPolymorphism in java
Polymorphism in java
 
PHP - Introduction to Object Oriented Programming with PHP
PHP -  Introduction to  Object Oriented Programming with PHPPHP -  Introduction to  Object Oriented Programming with PHP
PHP - Introduction to Object Oriented Programming with PHP
 
Classes&amp;objects
Classes&amp;objectsClasses&amp;objects
Classes&amp;objects
 

Viewers also liked

Heredity revised guided discussion 3 5-08
Heredity revised guided discussion 3 5-08Heredity revised guided discussion 3 5-08
Heredity revised guided discussion 3 5-08Mark Daniel Alcazar
 
Mobilizers Training
Mobilizers TrainingMobilizers Training
Mobilizers TrainingChandan Rout
 
Garcia & Lepage 2013 Methods for Scenario Development
Garcia & Lepage 2013 Methods for Scenario DevelopmentGarcia & Lepage 2013 Methods for Scenario Development
Garcia & Lepage 2013 Methods for Scenario DevelopmentClaude Garcia
 
The Art of the Wargame-Black Hat Reviews-APMP 2011-Pat Brosey 6-1-11
The Art of the Wargame-Black Hat Reviews-APMP 2011-Pat Brosey 6-1-11The Art of the Wargame-Black Hat Reviews-APMP 2011-Pat Brosey 6-1-11
The Art of the Wargame-Black Hat Reviews-APMP 2011-Pat Brosey 6-1-11Lohfeld Consulting Group
 
Visualizing the Navy Planning Process
Visualizing the Navy Planning ProcessVisualizing the Navy Planning Process
Visualizing the Navy Planning ProcessAquinicumPress
 
Hypermedia Discourse: Theory & Technology for the Pragmatic Web?
Hypermedia Discourse: Theory & Technology for the Pragmatic Web?Hypermedia Discourse: Theory & Technology for the Pragmatic Web?
Hypermedia Discourse: Theory & Technology for the Pragmatic Web?Simon Buckingham Shum
 
Rick Barron: User Experience Testing Methods
Rick Barron: User Experience Testing MethodsRick Barron: User Experience Testing Methods
Rick Barron: User Experience Testing MethodsRick Barron
 
Working group1
Working group1Working group1
Working group1Rex Brynen
 
Haiti Earthquake HADR Scenario
Haiti Earthquake HADR ScenarioHaiti Earthquake HADR Scenario
Haiti Earthquake HADR ScenarioRex Brynen
 
Military Decision Making Process (Mar 08) 3
Military Decision Making Process (Mar 08) 3Military Decision Making Process (Mar 08) 3
Military Decision Making Process (Mar 08) 3Thomas cleary
 
Military Decision Making Process (Mar 08) 2
Military Decision Making Process (Mar 08) 2Military Decision Making Process (Mar 08) 2
Military Decision Making Process (Mar 08) 2Thomas cleary
 
Active Competitive Intelligence
Active Competitive IntelligenceActive Competitive Intelligence
Active Competitive IntelligenceJeremy Horn
 
Scenario planning and transmedia storytelling ocad july 31 slideshare
Scenario planning and transmedia storytelling ocad july 31 slideshareScenario planning and transmedia storytelling ocad july 31 slideshare
Scenario planning and transmedia storytelling ocad july 31 slideshareZhan Li
 
OO Development 1 - Introduction to Object-Oriented Development
OO Development 1 - Introduction to Object-Oriented DevelopmentOO Development 1 - Introduction to Object-Oriented Development
OO Development 1 - Introduction to Object-Oriented DevelopmentRandy Connolly
 
Space policy theoretical space wargame software-unclassified
Space policy theoretical space wargame software-unclassifiedSpace policy theoretical space wargame software-unclassified
Space policy theoretical space wargame software-unclassifiedPaul Szymanski
 

Viewers also liked (20)

Heredity revised guided discussion 3 5-08
Heredity revised guided discussion 3 5-08Heredity revised guided discussion 3 5-08
Heredity revised guided discussion 3 5-08
 
Traits slide,5.12.2012
Traits slide,5.12.2012Traits slide,5.12.2012
Traits slide,5.12.2012
 
All about scala
All about scalaAll about scala
All about scala
 
Mobilizers Training
Mobilizers TrainingMobilizers Training
Mobilizers Training
 
Scenario Methodoology
Scenario MethodoologyScenario Methodoology
Scenario Methodoology
 
Garcia & Lepage 2013 Methods for Scenario Development
Garcia & Lepage 2013 Methods for Scenario DevelopmentGarcia & Lepage 2013 Methods for Scenario Development
Garcia & Lepage 2013 Methods for Scenario Development
 
The Art of the Wargame-Black Hat Reviews-APMP 2011-Pat Brosey 6-1-11
The Art of the Wargame-Black Hat Reviews-APMP 2011-Pat Brosey 6-1-11The Art of the Wargame-Black Hat Reviews-APMP 2011-Pat Brosey 6-1-11
The Art of the Wargame-Black Hat Reviews-APMP 2011-Pat Brosey 6-1-11
 
Visualizing the Navy Planning Process
Visualizing the Navy Planning ProcessVisualizing the Navy Planning Process
Visualizing the Navy Planning Process
 
The Foresight method for scenario building
The Foresight method for scenario buildingThe Foresight method for scenario building
The Foresight method for scenario building
 
Hypermedia Discourse: Theory & Technology for the Pragmatic Web?
Hypermedia Discourse: Theory & Technology for the Pragmatic Web?Hypermedia Discourse: Theory & Technology for the Pragmatic Web?
Hypermedia Discourse: Theory & Technology for the Pragmatic Web?
 
Rick Barron: User Experience Testing Methods
Rick Barron: User Experience Testing MethodsRick Barron: User Experience Testing Methods
Rick Barron: User Experience Testing Methods
 
Working group1
Working group1Working group1
Working group1
 
Haiti Earthquake HADR Scenario
Haiti Earthquake HADR ScenarioHaiti Earthquake HADR Scenario
Haiti Earthquake HADR Scenario
 
Mdmp How To Guide
Mdmp How To GuideMdmp How To Guide
Mdmp How To Guide
 
Military Decision Making Process (Mar 08) 3
Military Decision Making Process (Mar 08) 3Military Decision Making Process (Mar 08) 3
Military Decision Making Process (Mar 08) 3
 
Military Decision Making Process (Mar 08) 2
Military Decision Making Process (Mar 08) 2Military Decision Making Process (Mar 08) 2
Military Decision Making Process (Mar 08) 2
 
Active Competitive Intelligence
Active Competitive IntelligenceActive Competitive Intelligence
Active Competitive Intelligence
 
Scenario planning and transmedia storytelling ocad july 31 slideshare
Scenario planning and transmedia storytelling ocad july 31 slideshareScenario planning and transmedia storytelling ocad july 31 slideshare
Scenario planning and transmedia storytelling ocad july 31 slideshare
 
OO Development 1 - Introduction to Object-Oriented Development
OO Development 1 - Introduction to Object-Oriented DevelopmentOO Development 1 - Introduction to Object-Oriented Development
OO Development 1 - Introduction to Object-Oriented Development
 
Space policy theoretical space wargame software-unclassified
Space policy theoretical space wargame software-unclassifiedSpace policy theoretical space wargame software-unclassified
Space policy theoretical space wargame software-unclassified
 

Similar to Inheritance Mixins & Traits

Question and answer Programming
Question and answer ProgrammingQuestion and answer Programming
Question and answer ProgrammingInocentshuja Ahmad
 
Application package
Application packageApplication package
Application packageJAYAARC
 
Oop features java presentationshow
Oop features java presentationshowOop features java presentationshow
Oop features java presentationshowilias ahmed
 
Easymock Tutorial
Easymock TutorialEasymock Tutorial
Easymock TutorialSbin m
 
Object Oriended Programming with Java
Object Oriended Programming with JavaObject Oriended Programming with Java
Object Oriended Programming with JavaJakir Hossain
 
Obect-Oriented Collaboration
Obect-Oriented CollaborationObect-Oriented Collaboration
Obect-Oriented CollaborationAlena Holligan
 
Object oriented javascript
Object oriented javascriptObject oriented javascript
Object oriented javascriptUsman Mehmood
 
Object_oriented_programming_OOP_with_PHP.pdf
Object_oriented_programming_OOP_with_PHP.pdfObject_oriented_programming_OOP_with_PHP.pdf
Object_oriented_programming_OOP_with_PHP.pdfGammingWorld2
 
Jedi slides 2.1 object-oriented concepts
Jedi slides 2.1 object-oriented conceptsJedi slides 2.1 object-oriented concepts
Jedi slides 2.1 object-oriented conceptsMaryo Manjaruni
 
Android Training (Java Review)
Android Training (Java Review)Android Training (Java Review)
Android Training (Java Review)Khaled Anaqwa
 

Similar to Inheritance Mixins & Traits (20)

Unit3 part1-class
Unit3 part1-classUnit3 part1-class
Unit3 part1-class
 
Question and answer Programming
Question and answer ProgrammingQuestion and answer Programming
Question and answer Programming
 
Application package
Application packageApplication package
Application package
 
Actionscript
ActionscriptActionscript
Actionscript
 
Classes2
Classes2Classes2
Classes2
 
Oop features java presentationshow
Oop features java presentationshowOop features java presentationshow
Oop features java presentationshow
 
Java basics
Java basicsJava basics
Java basics
 
Easymock Tutorial
Easymock TutorialEasymock Tutorial
Easymock Tutorial
 
Object Oriended Programming with Java
Object Oriended Programming with JavaObject Oriended Programming with Java
Object Oriended Programming with Java
 
Delphi qa
Delphi qaDelphi qa
Delphi qa
 
Oops
OopsOops
Oops
 
Clean Code
Clean CodeClean Code
Clean Code
 
Design patterns
Design patternsDesign patterns
Design patterns
 
C# Unit 2 notes
C# Unit 2 notesC# Unit 2 notes
C# Unit 2 notes
 
Obect-Oriented Collaboration
Obect-Oriented CollaborationObect-Oriented Collaboration
Obect-Oriented Collaboration
 
Object oriented javascript
Object oriented javascriptObject oriented javascript
Object oriented javascript
 
Inheritance
InheritanceInheritance
Inheritance
 
Object_oriented_programming_OOP_with_PHP.pdf
Object_oriented_programming_OOP_with_PHP.pdfObject_oriented_programming_OOP_with_PHP.pdf
Object_oriented_programming_OOP_with_PHP.pdf
 
Jedi slides 2.1 object-oriented concepts
Jedi slides 2.1 object-oriented conceptsJedi slides 2.1 object-oriented concepts
Jedi slides 2.1 object-oriented concepts
 
Android Training (Java Review)
Android Training (Java Review)Android Training (Java Review)
Android Training (Java Review)
 

Recently uploaded

%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...masabamasaba
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastPapp Krisztián
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is insideshinachiaurasa2
 
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...Nitya salvi
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfonteinmasabamasaba
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionOnePlan Solutions
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareJim McKeeth
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdfPearlKirahMaeRagusta1
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfkalichargn70th171
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park masabamasaba
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park masabamasaba
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Hararemasabamasaba
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension AidPhilip Schwarz
 
%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durbanmasabamasaba
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfonteinmasabamasaba
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesVictorSzoltysek
 

Recently uploaded (20)

%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 

Inheritance Mixins & Traits

  • 1. When Inheritance is not enough. Mixins and others ways to reuse code. Maximiliano Fierro @elmasse
  • 2. Maximiliano Fierro Sr. Solution Engineer Co-Organizer
  • 4. ECMAScript is an Object Oriented Programing Language supporting delegating inheritance based on prototypes.
  • 5. What does it mean?
  • 6. Every Object references a Prototype [[Prototype]]: Internal property pointing to the object prototype. Some implementations provide the non- standard __proto__ as explicit reference.
  • 7. // Constructor function MyClass (msg) { this.msg = msg; }; // Instance method MyClass.prototype.foo = function () { console.log(this.msg); }; var a = new MyClass(‘Hello!’); a.foo(); // Hello! MyClass.prototype foo() [[Prototype] ] msg a [[Prototype] ] [[Prototype] ] Object.prototype null ...
  • 8. // Constructor function ClassA () { // call parent constructor MyClass.apply(this, arguments); }; // inherit from MyClass ClassA.prototype = Object.create(MyClass.prototype); // Instance method ClassA.prototype.bar = function () { console.log(this.msg + ‘ from bar’); }; var obj = new ClassA(‘Hello!’); obj.foo(); // Hello! obj.bar(); // Hello! from bar MyClass.prototype foo() ClassA.prototype bar() [[Prototype]] [[Prototype]] msg obj
  • 9. “Using inheritance as a vehicle to reuse code is a bit like ordering a happy meal because you want the plastic toy” Angus Croll.
  • 10. Abstract* / Base* Classes When inheriting from a Framework / Library Class (e.g. Views, Components, Controllers) and you find common methods or repeated code in several subclasses, often a Base Class is created to “share” that common code.
  • 11. Problems Abstract/Base Classes Deep hierarchy. The Base/Abstract Class becomes a “bag of common functions”.
  • 12. Reusing Functions Every (public) function can be invoked with .call or .apply
  • 13. It’s OK for simple functions... var max = Math.max.apply(null, array);
  • 14. … but code becomes wordy var instance = { msg: ‘Hello from instance’ }; //borrowing foo method from MyClass MyClass.prototype.foo.apply(instance); // Hello from instance //borrowing bar method from ClassA ClassA.prototype.bar.apply(instance); // Hello from instance from bar //borrowing foo method from ClassA inherited from MyClass ClassA.prototype.foo.apply(instance); // Hello from instance
  • 16. What is a Mixin? A Mixin is a class that is, often, not intended to be instantiated, but is combined into another class. Usually it is merged into a Class. In JavaScript, we can use Objects as Mixins.
  • 17. Mixins: Benefits Encourage code reuse. Can be seen as a workaround for Multiple Inheritance. Avoid the inheritance ambiguity (The diamond problem) linearly.
  • 18. Implementation Using Object.assign (or polyfill) - The Mixin is merged into the Class prototype. - Mixin can be Class or Object
  • 19. function MixedClass () { // call mixin constructor MyClass.apply(this, arguments); }; // apply Mixin Object.assign(MixedClass.prototype, MyClass.prototype); // Instance method MixedClass.prototype.bar = function () { console.log(this.msg + ‘ from bar’); }; var obj = new MixedClass(‘Hello!’); obj.foo(); // Hello! obj.bar(); // Hello! from bar MixedClass.prototype foo() [[Prototype] ] msg obj [[Prototype] ] [[Prototype] ] Object.prototype null ... bar()
  • 20. EventEmitter as a Mixin function MyClass() { // call Mixin constructor EventEmitter.call(this, arguments); } Object.assign(MyClass.prototype, EventEmitter.prototype); var obj = new MyClass(); obj.on(‘event’, function ( ) { console.log(‘event!’); }); obj.emit(‘event’);
  • 21. Functional Mixins Mixin is not a class but a function that decorates the prototype thru “this” keyword.
  • 22. // Functional Mixin function WithFoo() { this.foo = function () { console.log(this.msg); } return this; } // MixedClass definition function MixedClass(msg) { this.msg = msg; } // Apply Mixin WithFoo.call(MixedClass.prototype); MixedClass.prototype.bar = function () { console.log(this.msg + ‘ from bar’); }; var obj = new MixedClass(‘Hello!’); obj.foo(); // Hello! obj.bar(); // Hello! from bar
  • 23. The Diamond Problem BaseClass ClassA ClassB DerivedClass foo() var d = new DerivedClass(); d.foo() // which foo ?? ... ... ... foo()
  • 24. The Diamond Problem cont’d Object.assign(DerivedClass.prototype, ClassA.prototype, ClassB.prototype); var d = new DerivedClass(); d.foo() // from ClassB Object.assign(DerivedClass.prototype, ClassB.prototype, ClassA.prototype); var d = new DerivedClass(); d.foo() // from ClassA
  • 25. Calling an Overridden Method …. Object.assign(DerivedClass.prototype, ClassA.prototype, ClassB.prototype); DerivedClass.prototype.foo = function() { // call “overridden” foo from A ClassA.prototype.foo.apply(this, arguments); }
  • 26. Problems Methods and properties are overridden based on declaration position / implementation. Refactoring (adding/renaming methods) can cause “silent issues”. Calling an overridden method is wordy and error prone.
  • 28. What is a Trait? Composable Units of Behavior. A special type of class with no state. Can be seen as Incomplete classes. Defines behavior and access state thru required accessors.
  • 29. Class = Traits + Glue Code + State (+ SuperClass)
  • 30. Composing Behavior May require a set of methods to serve as parameters for the provided behavior. (Incomplete Classes) Can be composed from other traits. Name collision is solved by the Developer (aliases or exclusions)
  • 31. Conflict Resolution Conflict arises when we combine two or more traits providing identically named methods that do not originate from the same trait. Alias: A conflicting method can be “renamed”. Exclusion: We can solve the conflict by just excluding the method explicitly.
  • 32. MyList.prototype +getCollection() [[Prototype] ] withFirst <Trait> first() *getCollection() withLast <Trait> last() *getCollection() withIterator <Trait> iterator() *getCollection() @traits [[Prototype] ] collection: [1,2,3,4,5] list var list = new MyList([1,2,3,4,5]); console.log('collection: ', list.getCollection()); // [1,2,3,4,5] console.log('first: ', list.first()); // 1 console.log('last: ', list.last()); // 5 console.log('iterate:'); var iterator = list.iterator(); var value; while(value = iterator.next()){ console.log(value); } (*) Required Method (+) Glue Code
  • 34. MyList.prototype getCollection(): {Array} [[Prototype] ] withFirst <Trait> first() *getCollection() withLast <Trait> last() *getCollection() withIterator <Trait> iterator() *getCollection() @traits [[Prototype] ] collection: [1,2,3,4,5] list var list = new MyList([1,2,3,4,5]); console.log('collection: ', list.getCollection()); // [1,2,3,4,5] console.log('first: ', list.first()); // 1 console.log('last: ', list.last()); // 5 console.log('iterate:'); var iterator = list.iterator(); var value; while(value = iterator.next()){ console.log(value); } iterable <Trait>
  • 35. MyList.prototype getCollection(): {Array} [[Prototype] ] withFirst <Trait> first() *getCollection() withLast <Trait> last() *getCollection() withIterator <Trait> iterator() *getCollection() @traits [[Prototype] ] collection: [1,2,3,4,5] list ERROR! method “first” is defined twice! iterable <Trait> first()
  • 36. Conflict Resolution: Alias or Exclude we can exclude “first” from the iterable Trait or rename it in case we want to use it.
  • 38. CocktailJS npm install -s cocktail cocktailjs.github.io
  • 40. Demo

Editor's Notes

  1. Today I’m gonna talk about … A little introduction about me
  2. Objects are created via constructors. Constructor is a function that creates and initializes the newly created object.
  3. call -> c for comma separated apply -> a for arguments