SlideShare une entreprise Scribd logo
1  sur  53
OOP in JS
     Revisited


  Eugene Lazutkin

ClubAjax on 6/5/2012
    Dallas, TX
About me
• Eugene Lazutkin
• Open Source web developer
   • Majors: JavaScript & Python, Dojo & Django.
• Independent consultant
• Blog: lazutkin.com
• Twitter: @uhop, Google+: gplus.to/uhop
Prerequisites


• Basic knowledge of object-oriented programming
  is required.
• Basic knowledge of JavaScript version of OOP is
  assumed.
OOP foundation

• The foundation of OOP is an object.
    • No, not a class or any other entity.
• Object incapsulates its state.
    • OOP is a technique for an imperative
      programming.
OOP foundation
• Object comes with methods (functions) that can use
  or modify its state.
• Objects are used to partition a program state into
  manageable pieces.
• Ultimate goal is to reduce the overall complexity.
   • Instead of huge state space we deal with a
     smaller number of objects w/ compact API.
Reducing complexity

• While the whole state space can be huge, not all
  states are possible:
   • There are certain conditions that should be
     satisfied for a state to make sense.
   • Operations on objects may have pre- and post-
     conditions.
Example: car


• Car is much more than a
  sum of its parts.

• How parts fit together is an
  invariant.
Example: car


• Is it a car?

    • No, its invariant is
      violated.
Invariants
• It is a good practice to enforce invariants.
    • Object methods should not violate invariants.
    • Only constructor and destructor can violate
      them.
      • Constructor builds an object from a certain
        state.
      • After destructor an object cannot be used.
Program state

• Imagine that we can observe
  program's state and how it
  changes over time.

• Now imagine that we
  partitioned this space into a
  finite number of objects.
Program state

• Some objects can be very
  similar to others.

    • The same class.

• Some objects have
  similarities yet not of the
  same class.

    • Related classes.
What is a class?

• A recipe for an object, which can be reused.
• An object pattern expressed in some declarative
  form.
• A factory function, which can produce similar
  objects.
Class relations


• How to model relationship between classes?
   • One popular way to do that is a single
     inheritance.
   • JavaScript does the same with delegation.
Class relations

• How single inheritance (SI) work:
   • A base class provides some state (member
     variables) and a set of operations on it
     (methods).
   • A derived class adds its own state chunk and its
     own methods.
SI: invariants

• A derived object can be classified as being of the
  base class, and of the derived class at the same
  time.
   • Both class invariants should be satisfied at the
     same time.
   • Methods of the derived class should not violate
     the base class invariant.
SI: life cycle
• A derived class constructor usually assumes that it
  started with a valid base object building on it.
• When a derived destructor has finished, it leaves a
  valid base class object.
• Usually there is a primordial Object class, which is
  the basest foundation for any other class.
   • In JavaScript it is {}.
Destructors
• Why do we need to destroy an object? Isn't it
  excessive in the age of garbage collection?
   • Objects may have references to physical
     resources, which has to be freed (network
     connections, files, USB devices, and so on).
   • Objects may have known references to them
     from other long-lived objects, preventing them
     to be garbage-collected.
Chaining

• Invariant requirements assume chaining:
   • Base class constructor should run before
     derived constructor.
   • Base class destructor should run after derived
     destructor.
Chaining

• Invariant requirements assume chaining:
   • Derived methods that update its own state in
     response to base class changes usually should
     run after its base class counterparts.
   • Derived methods that set up its state to ride side
     effects of base class changes should run before.
Chaining
• Invariant requirements assume chaining:
   • Derived methods that update its state
     independently from base class changes usually
     run before or after.
   • Derived methods that should update its base
     state to satisfy the base invariant usually do
     that, then call its base method, then update
     state back according to the derived invariant.
Chaining

• All types of chaining can be done manually with
  super calls.
• Manual super calls can be error-prone.
• Manual super calls in constructors are extremely
  error-prone, especially when refactoring.
Super call problem

• Constructor super call problem:
   • JavaScript objects are open: I can access
     whatever member variable I want.
   • Imagine I know how my base class is
     constructed, so instead of calling its constructor
     I decided to initialize all necessary variables in
     the derived constructor.
Super call problem

• Constructor super call problem:
   • Now every time I change my base class I have
     to hunt down "smart" derived classes and
     modify them too.
   • The same goes for bypassed methods.
Super calls

• There are two ways to do super calls:
   • Call a base method explicitly.
   • Call a base method implicitly.
• JavaScript only supports explicit calls.
   • There is a class proposal in works for ES6 that
     introduces implicit super calls.
OOP fail


• Sometimes it does.
• Let’s look at some practical criticism of OOP.
Complexity fail #1

• OOP doesn't scale down. You are better off writing
  simple programs without it.
• Example: the official "Hello, world!" in Java:
class HelloWorldApp {
public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}
Complexity fail #1
• Do we really need a named class, with a static
  method?
• Additional conclusion: in JS you will need OOP
  when your program is big enough ⇒ stop worrying
  about the size of OOP package you use, look for
  completeness and correctness of its
  implementation.
SI fail
• Who said that a single inheritance is the only form
  of a relationship between classes?
   • Trying to use a hammer (a single inheritance)
     for all problems leads to poor code reuse:
      • Cut-and-paste code.
      • Duplication of methods.
      • Top heavy hierarchy with stubbed methods.
SI fail

• Example:
   • A fish, a duck, a hippo, and a submarine can
     swim.
   • Does it mean that they have a common
     swimming ancestor?
Complexity fail #2


• OOP doesn't scale up.
   • It is not a technical limitation, it is a human
     limitation.
   • People are bad at constructing big hierarchies.
History lessons

• Plato:

    • Mentored by Socrates.

    • Mentor of Aristotle.

    • First major attempt to
      understand the
      classification problem in
      his "theory of forms".
History lessons

• Aristotle

    • Mentored by Plato.

    • Mentor of Alexander
      the Great.

    • "Corrected" Plato's
      theory in over 170 of
      his works!
History lessons

• Since 18th century
  numerous philosophers
  criticized predecessors and
  offered different strategies of
  classification.

• The work is not finished yet.
Methodology fail

• So how to classify objects? How to find objects in a
  soup of state space?
• Unless your domain has well-defined physical or
  logical entities, you are on your own.
• Examples of well-defined objects: physical objects,
  graphics, UI objects, tax forms, and so on.
What did we learn?
• Like all techniques OOP has its own sweet spot/
  applicability area.
   • It is not a universal tool. Do not abuse it.
• Single inheritance is very limited.
   • If it doesn't fit your project, you better look for
     alternatives.
• Keep your inheritance diagram compact.
SI alternatives
• One way to keep compact inheritance diagram is
  to move from a tree to a DAG:
   • AOP (crosscutting concerns).
   • Multiple inheritance (MI) (like in C++?).
   • Mixins (inherit from multiple bases using a
     DAG linearization technique).
   • Traits (mixin-like entities that scale up better).
SI alternatives
• Let's drop multiple inheritance.
    • JavaScript supports single inheritance natively,
      and DAG linearization would work better.
• Let's drop traits.
    • The full machinery is too complex.
    • Traits rely on some static analysis, while
      JavaScript is essentially dynamic.
SI augmentation: AOP

• Aspect-oriented programming (AOP) requires
  weaving methods using three types of advices:
  before, after, and around.
• "Before" and "after" advices are essentially
  chaining we already looked at before.
• "Around" advice is a super call.
SI augmentation: AOP


• In order to be flexible we should support two
  modes of weaving:
   • Static (when classes are composed).
   • Dynamic (when objects are advised).
SI augmentation:
            mixins
• Mixins can inject its own state, and support its own
  invariants.
   • Mixins may participate in an object life-cycle.
• Mixins can redefine existing methods, add new
  methods.
• Mixins rely on existing methods and member
  variables.
SI augmentation:
            mixins
• Any multiple inheritance technique produces an
  inheritance DAG and relies on its linearization (we
  don't run parallel bases in parallel).
• While a relative order of mixins can be specified,
  an absolute order is not defined.
   • Mixins cannot call base methods explicitly.
   • Implicit super calls are required.
SI augmentation:
            mixins

• In order to reuse JS existing single inheritance
  mechanisms we need to linearize an inheritance
  DAG.
   • C3 MRO (method resolution order) is the most
     popular and well-understood technique used in
     languages like Python.
What we want
• Reasonable requirements for OOP implementation
  so far:
   • Well-defined linearization (C3 MRO).
   • Chain constructors using "after" chaining
     automatically (optional).
   • Chain destructors using "before" chaining
     automatically (optional).
What we want
• Reasonable requirements for OOP implementation
  so far:
   • Anonymous/implicit super calls.
   • Before/after advices for methods during class
     composition.
   • Before/after/around advices for objects to
     weave dynamically.
Sample implementation
• New project that implements required functionality
  under development: dcl.
   • https://github.com/uhop/dcl
   • Runs on Node.js.
   • Runs with AMD-based loader (including Dojo
     1.7 and RequireJS).
   • Can be used stand-alone in a browser.
Sample implementation

• Based on proven Dojo technologies:
   • The venerable dojo.declare().
   • dojox/lang/aspect
   • dojox/lang/oo
• Like Dojo licensed under BSD and AFL.
dcl

• Currently consists of three modules:
   • mini.js
   • dcl.js
   • advise.js
dcl

• mini.js:
    • Provides automatic constructor chaining out of
      box.
    • Provides implicit super calls.
    • For byte-conscious: just over 900 bytes.
dcl

• dcl.js:
    • Adds “before” and “after” weaving for class
      methods.
    • Adds after/before chaining.
    • Intended to be used as a main module.
dcl

• advise.js:
    • Provides “before”, “after”, and “around”
      weaving for object methods.
    • Advices can be removed dynamically.
      • That’s the main difference with dcl’s advices.
dcl
• In works:
   • Special debugging version of said modules.
     • Nobody cares about how we debug libraries.
       It is time we do.
   • Micro-library of mixins and advices including:
     method timer, counter, tracer, memoizer, flow
     analyzer, and so on.
That’s all!
Picture credits

Car: http://www.flickr.com/photos/arcaist/2311533441/
Car parts: http://www.flickr.com/photos/7603557@N08/2662531345/
Voronoi diagram: http://en.wikipedia.org/wiki/File:2Ddim-L2norm-10site.png
Voronoi 3D: http://en.wikipedia.org/wiki/File:Coloured_Voronoi_3D_slice.png
Plato: http://en.wikipedia.org/wiki/File:Plato_Silanion_Musei_Capitolini_MC1377.jpg
Aristotle: http://en.wikipedia.org/wiki/File:Aristoteles_Louvre.jpg
Plato & Aristotle: http://en.wikipedia.org/wiki/File:Sanzio_01_Plato_Aristotle.jpg

Contenu connexe

Tendances

Intro to java programming
Intro to java programmingIntro to java programming
Intro to java programmingLeah Stephens
 
Into the Land of lambda, One Programmer's Journey Into Functional Programming
Into the Land of lambda, One Programmer's Journey Into Functional ProgrammingInto the Land of lambda, One Programmer's Journey Into Functional Programming
Into the Land of lambda, One Programmer's Journey Into Functional ProgrammingMike Pence
 
Ontology Engineering: ontology construction II
Ontology Engineering: ontology construction IIOntology Engineering: ontology construction II
Ontology Engineering: ontology construction IIGuus Schreiber
 
How to write a web framework
How to write a web frameworkHow to write a web framework
How to write a web frameworkNgoc Dao
 
2014 10-9-blogging genomesannotation
2014 10-9-blogging genomesannotation2014 10-9-blogging genomesannotation
2014 10-9-blogging genomesannotationYannick Wurm
 
How to R.E.A.D: Steps for how to select the correct module @NEWDCamp 2014
How to R.E.A.D: Steps for how to select the correct module @NEWDCamp 2014How to R.E.A.D: Steps for how to select the correct module @NEWDCamp 2014
How to R.E.A.D: Steps for how to select the correct module @NEWDCamp 2014Michael Miles
 
To Patch or Custom: How to decide when to patch a contrib module or go custom...
To Patch or Custom: How to decide when to patch a contrib module or go custom...To Patch or Custom: How to decide when to patch a contrib module or go custom...
To Patch or Custom: How to decide when to patch a contrib module or go custom...Michael Miles
 
GeekAustin PHP Class - Session 6
GeekAustin PHP Class - Session 6GeekAustin PHP Class - Session 6
GeekAustin PHP Class - Session 6jimbojsb
 
Deploying Rails Applications: Lessons Learned
Deploying Rails Applications: Lessons LearnedDeploying Rails Applications: Lessons Learned
Deploying Rails Applications: Lessons LearnedMichael Koby
 

Tendances (11)

Intro to java programming
Intro to java programmingIntro to java programming
Intro to java programming
 
Into the Land of lambda, One Programmer's Journey Into Functional Programming
Into the Land of lambda, One Programmer's Journey Into Functional ProgrammingInto the Land of lambda, One Programmer's Journey Into Functional Programming
Into the Land of lambda, One Programmer's Journey Into Functional Programming
 
Ontology Engineering: ontology construction II
Ontology Engineering: ontology construction IIOntology Engineering: ontology construction II
Ontology Engineering: ontology construction II
 
How to write a web framework
How to write a web frameworkHow to write a web framework
How to write a web framework
 
2014 10-9-blogging genomesannotation
2014 10-9-blogging genomesannotation2014 10-9-blogging genomesannotation
2014 10-9-blogging genomesannotation
 
Java and the JVM
Java and the JVMJava and the JVM
Java and the JVM
 
How to R.E.A.D: Steps for how to select the correct module @NEWDCamp 2014
How to R.E.A.D: Steps for how to select the correct module @NEWDCamp 2014How to R.E.A.D: Steps for how to select the correct module @NEWDCamp 2014
How to R.E.A.D: Steps for how to select the correct module @NEWDCamp 2014
 
To Patch or Custom: How to decide when to patch a contrib module or go custom...
To Patch or Custom: How to decide when to patch a contrib module or go custom...To Patch or Custom: How to decide when to patch a contrib module or go custom...
To Patch or Custom: How to decide when to patch a contrib module or go custom...
 
GeekAustin PHP Class - Session 6
GeekAustin PHP Class - Session 6GeekAustin PHP Class - Session 6
GeekAustin PHP Class - Session 6
 
12. Objects I
12. Objects I12. Objects I
12. Objects I
 
Deploying Rails Applications: Lessons Learned
Deploying Rails Applications: Lessons LearnedDeploying Rails Applications: Lessons Learned
Deploying Rails Applications: Lessons Learned
 

En vedette

[Frontend 101] JavaScript OOP
[Frontend 101] JavaScript OOP[Frontend 101] JavaScript OOP
[Frontend 101] JavaScript OOPMaxis Kao
 
الحياة والبرمجة كائنية التوجه
الحياة والبرمجة كائنية التوجهالحياة والبرمجة كائنية التوجه
الحياة والبرمجة كائنية التوجهAnees Abu hmaid
 
باللغة العربية jQuery دورة
 باللغة العربية jQuery دورة باللغة العربية jQuery دورة
باللغة العربية jQuery دورةanees abu-hmaid
 
Canvas دورة باللغة العربية
Canvas دورة باللغة العربيةCanvas دورة باللغة العربية
Canvas دورة باللغة العربيةanees abu-hmaid
 
Bootstrap3 دورة باللغة العربية
Bootstrap3 دورة باللغة العربيةBootstrap3 دورة باللغة العربية
Bootstrap3 دورة باللغة العربيةanees abu-hmaid
 
Modern JavaScript Applications: Design Patterns
Modern JavaScript Applications: Design PatternsModern JavaScript Applications: Design Patterns
Modern JavaScript Applications: Design PatternsVolodymyr Voytyshyn
 

En vedette (8)

[Frontend 101] JavaScript OOP
[Frontend 101] JavaScript OOP[Frontend 101] JavaScript OOP
[Frontend 101] JavaScript OOP
 
الحياة والبرمجة كائنية التوجه
الحياة والبرمجة كائنية التوجهالحياة والبرمجة كائنية التوجه
الحياة والبرمجة كائنية التوجه
 
jQuery UI (Effect)
jQuery UI (Effect) jQuery UI (Effect)
jQuery UI (Effect)
 
باللغة العربية jQuery دورة
 باللغة العربية jQuery دورة باللغة العربية jQuery دورة
باللغة العربية jQuery دورة
 
Canvas دورة باللغة العربية
Canvas دورة باللغة العربيةCanvas دورة باللغة العربية
Canvas دورة باللغة العربية
 
Bootstrap3 دورة باللغة العربية
Bootstrap3 دورة باللغة العربيةBootstrap3 دورة باللغة العربية
Bootstrap3 دورة باللغة العربية
 
Js dom & JS bom
Js dom & JS bomJs dom & JS bom
Js dom & JS bom
 
Modern JavaScript Applications: Design Patterns
Modern JavaScript Applications: Design PatternsModern JavaScript Applications: Design Patterns
Modern JavaScript Applications: Design Patterns
 

Similaire à OOP in JS

[OOP - Lec 04,05] Basic Building Blocks of OOP
[OOP - Lec 04,05] Basic Building Blocks of OOP[OOP - Lec 04,05] Basic Building Blocks of OOP
[OOP - Lec 04,05] Basic Building Blocks of OOPMuhammad Hammad Waseem
 
2009 training - tim m - object oriented programming
2009   training - tim m - object oriented programming2009   training - tim m - object oriented programming
2009 training - tim m - object oriented programmingTim Mahy
 
Orthogonality: A Strategy for Reusable Code
Orthogonality: A Strategy for Reusable CodeOrthogonality: A Strategy for Reusable Code
Orthogonality: A Strategy for Reusable Codersebbe
 
Complete PPT about the Java lokesh kept it
Complete PPT about the Java lokesh kept itComplete PPT about the Java lokesh kept it
Complete PPT about the Java lokesh kept itlokeshpappaka10
 
12_oop templa.pptx
12_oop templa.pptx12_oop templa.pptx
12_oop templa.pptxRokaKaram
 
Object Oriented Programming
Object Oriented ProgrammingObject Oriented Programming
Object Oriented ProgrammingRatnaJava
 
Working With Concurrency In Java 8
Working With Concurrency In Java 8Working With Concurrency In Java 8
Working With Concurrency In Java 8Heartin Jacob
 
SKILLWISE - OOPS CONCEPT
SKILLWISE - OOPS CONCEPTSKILLWISE - OOPS CONCEPT
SKILLWISE - OOPS CONCEPTSkillwise Group
 
Kevin Whinnery: Write Better JavaScript
Kevin Whinnery: Write Better JavaScriptKevin Whinnery: Write Better JavaScript
Kevin Whinnery: Write Better JavaScriptAxway Appcelerator
 
Javascript classes and scoping
Javascript classes and scopingJavascript classes and scoping
Javascript classes and scopingPatrick Sheridan
 
Chapter 4_Introduction to Patterns.ppt
Chapter 4_Introduction to Patterns.pptChapter 4_Introduction to Patterns.ppt
Chapter 4_Introduction to Patterns.pptRushikeshChikane1
 
Chapter 4_Introduction to Patterns.ppt
Chapter 4_Introduction to Patterns.pptChapter 4_Introduction to Patterns.ppt
Chapter 4_Introduction to Patterns.pptRushikeshChikane2
 
Java Closures
Java ClosuresJava Closures
Java ClosuresBen Evans
 
Intro to oop.pptx
Intro to oop.pptxIntro to oop.pptx
Intro to oop.pptxUmerUmer25
 
Hello, React Hooks!
Hello, React Hooks!Hello, React Hooks!
Hello, React Hooks!Heejong Ahn
 

Similaire à OOP in JS (20)

[OOP - Lec 04,05] Basic Building Blocks of OOP
[OOP - Lec 04,05] Basic Building Blocks of OOP[OOP - Lec 04,05] Basic Building Blocks of OOP
[OOP - Lec 04,05] Basic Building Blocks of OOP
 
2009 training - tim m - object oriented programming
2009   training - tim m - object oriented programming2009   training - tim m - object oriented programming
2009 training - tim m - object oriented programming
 
Orthogonality: A Strategy for Reusable Code
Orthogonality: A Strategy for Reusable CodeOrthogonality: A Strategy for Reusable Code
Orthogonality: A Strategy for Reusable Code
 
Complete PPT about the Java lokesh kept it
Complete PPT about the Java lokesh kept itComplete PPT about the Java lokesh kept it
Complete PPT about the Java lokesh kept it
 
2CPP19 - Summation
2CPP19 - Summation2CPP19 - Summation
2CPP19 - Summation
 
12_oop templa.pptx
12_oop templa.pptx12_oop templa.pptx
12_oop templa.pptx
 
Object Oriented Programming
Object Oriented ProgrammingObject Oriented Programming
Object Oriented Programming
 
Working With Concurrency In Java 8
Working With Concurrency In Java 8Working With Concurrency In Java 8
Working With Concurrency In Java 8
 
Design p atterns
Design p atternsDesign p atterns
Design p atterns
 
SKILLWISE - OOPS CONCEPT
SKILLWISE - OOPS CONCEPTSKILLWISE - OOPS CONCEPT
SKILLWISE - OOPS CONCEPT
 
Kevin Whinnery: Write Better JavaScript
Kevin Whinnery: Write Better JavaScriptKevin Whinnery: Write Better JavaScript
Kevin Whinnery: Write Better JavaScript
 
Javascript classes and scoping
Javascript classes and scopingJavascript classes and scoping
Javascript classes and scoping
 
Introduction to c ++ part -1
Introduction to c ++   part -1Introduction to c ++   part -1
Introduction to c ++ part -1
 
Chapter 4_Introduction to Patterns.ppt
Chapter 4_Introduction to Patterns.pptChapter 4_Introduction to Patterns.ppt
Chapter 4_Introduction to Patterns.ppt
 
Chapter 4_Introduction to Patterns.ppt
Chapter 4_Introduction to Patterns.pptChapter 4_Introduction to Patterns.ppt
Chapter 4_Introduction to Patterns.ppt
 
CONSTRUCTORS.pptx
CONSTRUCTORS.pptxCONSTRUCTORS.pptx
CONSTRUCTORS.pptx
 
[OOP - Lec 06] Classes and Objects
[OOP - Lec 06] Classes and Objects[OOP - Lec 06] Classes and Objects
[OOP - Lec 06] Classes and Objects
 
Java Closures
Java ClosuresJava Closures
Java Closures
 
Intro to oop.pptx
Intro to oop.pptxIntro to oop.pptx
Intro to oop.pptx
 
Hello, React Hooks!
Hello, React Hooks!Hello, React Hooks!
Hello, React Hooks!
 

Plus de Eugene Lazutkin

Functional practices in JavaScript
Functional practices in JavaScriptFunctional practices in JavaScript
Functional practices in JavaScriptEugene Lazutkin
 
Express: the web server for node.js
Express: the web server for node.jsExpress: the web server for node.js
Express: the web server for node.jsEugene Lazutkin
 
Practical pairing of generative programming with functional programming.
Practical pairing of generative programming with functional programming.Practical pairing of generative programming with functional programming.
Practical pairing of generative programming with functional programming.Eugene Lazutkin
 
Optimization of modern web applications
Optimization of modern web applicationsOptimization of modern web applications
Optimization of modern web applicationsEugene Lazutkin
 
SSJS, NoSQL, GAE and AppengineJS
SSJS, NoSQL, GAE and AppengineJSSSJS, NoSQL, GAE and AppengineJS
SSJS, NoSQL, GAE and AppengineJSEugene Lazutkin
 
Dojo for programmers (TXJS 2010)
Dojo for programmers (TXJS 2010)Dojo for programmers (TXJS 2010)
Dojo for programmers (TXJS 2010)Eugene Lazutkin
 
Exciting JavaScript - Part II
Exciting JavaScript - Part IIExciting JavaScript - Part II
Exciting JavaScript - Part IIEugene Lazutkin
 
Exciting JavaScript - Part I
Exciting JavaScript - Part IExciting JavaScript - Part I
Exciting JavaScript - Part IEugene Lazutkin
 
Dojo GFX workshop slides
Dojo GFX workshop slidesDojo GFX workshop slides
Dojo GFX workshop slidesEugene Lazutkin
 
Dojo GFX: SVG in the real world
Dojo GFX: SVG in the real worldDojo GFX: SVG in the real world
Dojo GFX: SVG in the real worldEugene Lazutkin
 
DojoX GFX Session Eugene Lazutkin SVG Open 2007
DojoX GFX Session Eugene Lazutkin SVG Open 2007DojoX GFX Session Eugene Lazutkin SVG Open 2007
DojoX GFX Session Eugene Lazutkin SVG Open 2007Eugene Lazutkin
 
DojoX GFX Keynote Eugene Lazutkin SVG Open 2007
DojoX GFX Keynote Eugene Lazutkin SVG Open 2007DojoX GFX Keynote Eugene Lazutkin SVG Open 2007
DojoX GFX Keynote Eugene Lazutkin SVG Open 2007Eugene Lazutkin
 

Plus de Eugene Lazutkin (20)

Service workers
Service workersService workers
Service workers
 
Advanced I/O in browser
Advanced I/O in browserAdvanced I/O in browser
Advanced I/O in browser
 
Streams
StreamsStreams
Streams
 
Functional practices in JavaScript
Functional practices in JavaScriptFunctional practices in JavaScript
Functional practices in JavaScript
 
Express: the web server for node.js
Express: the web server for node.jsExpress: the web server for node.js
Express: the web server for node.js
 
TXJS 2013 in 10 minutes
TXJS 2013 in 10 minutesTXJS 2013 in 10 minutes
TXJS 2013 in 10 minutes
 
Practical pairing of generative programming with functional programming.
Practical pairing of generative programming with functional programming.Practical pairing of generative programming with functional programming.
Practical pairing of generative programming with functional programming.
 
Optimization of modern web applications
Optimization of modern web applicationsOptimization of modern web applications
Optimization of modern web applications
 
Pulsar
PulsarPulsar
Pulsar
 
SSJS, NoSQL, GAE and AppengineJS
SSJS, NoSQL, GAE and AppengineJSSSJS, NoSQL, GAE and AppengineJS
SSJS, NoSQL, GAE and AppengineJS
 
Dojo for programmers (TXJS 2010)
Dojo for programmers (TXJS 2010)Dojo for programmers (TXJS 2010)
Dojo for programmers (TXJS 2010)
 
Exciting JavaScript - Part II
Exciting JavaScript - Part IIExciting JavaScript - Part II
Exciting JavaScript - Part II
 
RAD CRUD
RAD CRUDRAD CRUD
RAD CRUD
 
Exciting JavaScript - Part I
Exciting JavaScript - Part IExciting JavaScript - Part I
Exciting JavaScript - Part I
 
CRUD with Dojo
CRUD with DojoCRUD with Dojo
CRUD with Dojo
 
Dojo GFX workshop slides
Dojo GFX workshop slidesDojo GFX workshop slides
Dojo GFX workshop slides
 
Dojo GFX: SVG in the real world
Dojo GFX: SVG in the real worldDojo GFX: SVG in the real world
Dojo GFX: SVG in the real world
 
Dojo (QCon 2007 Slides)
Dojo (QCon 2007 Slides)Dojo (QCon 2007 Slides)
Dojo (QCon 2007 Slides)
 
DojoX GFX Session Eugene Lazutkin SVG Open 2007
DojoX GFX Session Eugene Lazutkin SVG Open 2007DojoX GFX Session Eugene Lazutkin SVG Open 2007
DojoX GFX Session Eugene Lazutkin SVG Open 2007
 
DojoX GFX Keynote Eugene Lazutkin SVG Open 2007
DojoX GFX Keynote Eugene Lazutkin SVG Open 2007DojoX GFX Keynote Eugene Lazutkin SVG Open 2007
DojoX GFX Keynote Eugene Lazutkin SVG Open 2007
 

Dernier

Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentPim van der Noll
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...AliaaTarek5
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Alkin Tezuysal
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
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
 
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
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
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
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesThousandEyes
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 

Dernier (20)

Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
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
 
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.
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
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
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 

OOP in JS

  • 1. OOP in JS Revisited Eugene Lazutkin ClubAjax on 6/5/2012 Dallas, TX
  • 2. About me • Eugene Lazutkin • Open Source web developer • Majors: JavaScript & Python, Dojo & Django. • Independent consultant • Blog: lazutkin.com • Twitter: @uhop, Google+: gplus.to/uhop
  • 3. Prerequisites • Basic knowledge of object-oriented programming is required. • Basic knowledge of JavaScript version of OOP is assumed.
  • 4. OOP foundation • The foundation of OOP is an object. • No, not a class or any other entity. • Object incapsulates its state. • OOP is a technique for an imperative programming.
  • 5. OOP foundation • Object comes with methods (functions) that can use or modify its state. • Objects are used to partition a program state into manageable pieces. • Ultimate goal is to reduce the overall complexity. • Instead of huge state space we deal with a smaller number of objects w/ compact API.
  • 6. Reducing complexity • While the whole state space can be huge, not all states are possible: • There are certain conditions that should be satisfied for a state to make sense. • Operations on objects may have pre- and post- conditions.
  • 7. Example: car • Car is much more than a sum of its parts. • How parts fit together is an invariant.
  • 8. Example: car • Is it a car? • No, its invariant is violated.
  • 9. Invariants • It is a good practice to enforce invariants. • Object methods should not violate invariants. • Only constructor and destructor can violate them. • Constructor builds an object from a certain state. • After destructor an object cannot be used.
  • 10. Program state • Imagine that we can observe program's state and how it changes over time. • Now imagine that we partitioned this space into a finite number of objects.
  • 11. Program state • Some objects can be very similar to others. • The same class. • Some objects have similarities yet not of the same class. • Related classes.
  • 12. What is a class? • A recipe for an object, which can be reused. • An object pattern expressed in some declarative form. • A factory function, which can produce similar objects.
  • 13. Class relations • How to model relationship between classes? • One popular way to do that is a single inheritance. • JavaScript does the same with delegation.
  • 14. Class relations • How single inheritance (SI) work: • A base class provides some state (member variables) and a set of operations on it (methods). • A derived class adds its own state chunk and its own methods.
  • 15. SI: invariants • A derived object can be classified as being of the base class, and of the derived class at the same time. • Both class invariants should be satisfied at the same time. • Methods of the derived class should not violate the base class invariant.
  • 16. SI: life cycle • A derived class constructor usually assumes that it started with a valid base object building on it. • When a derived destructor has finished, it leaves a valid base class object. • Usually there is a primordial Object class, which is the basest foundation for any other class. • In JavaScript it is {}.
  • 17. Destructors • Why do we need to destroy an object? Isn't it excessive in the age of garbage collection? • Objects may have references to physical resources, which has to be freed (network connections, files, USB devices, and so on). • Objects may have known references to them from other long-lived objects, preventing them to be garbage-collected.
  • 18. Chaining • Invariant requirements assume chaining: • Base class constructor should run before derived constructor. • Base class destructor should run after derived destructor.
  • 19. Chaining • Invariant requirements assume chaining: • Derived methods that update its own state in response to base class changes usually should run after its base class counterparts. • Derived methods that set up its state to ride side effects of base class changes should run before.
  • 20. Chaining • Invariant requirements assume chaining: • Derived methods that update its state independently from base class changes usually run before or after. • Derived methods that should update its base state to satisfy the base invariant usually do that, then call its base method, then update state back according to the derived invariant.
  • 21. Chaining • All types of chaining can be done manually with super calls. • Manual super calls can be error-prone. • Manual super calls in constructors are extremely error-prone, especially when refactoring.
  • 22. Super call problem • Constructor super call problem: • JavaScript objects are open: I can access whatever member variable I want. • Imagine I know how my base class is constructed, so instead of calling its constructor I decided to initialize all necessary variables in the derived constructor.
  • 23. Super call problem • Constructor super call problem: • Now every time I change my base class I have to hunt down "smart" derived classes and modify them too. • The same goes for bypassed methods.
  • 24. Super calls • There are two ways to do super calls: • Call a base method explicitly. • Call a base method implicitly. • JavaScript only supports explicit calls. • There is a class proposal in works for ES6 that introduces implicit super calls.
  • 25. OOP fail • Sometimes it does. • Let’s look at some practical criticism of OOP.
  • 26. Complexity fail #1 • OOP doesn't scale down. You are better off writing simple programs without it. • Example: the official "Hello, world!" in Java: class HelloWorldApp { public static void main(String[] args) { System.out.println("Hello World!"); } }
  • 27. Complexity fail #1 • Do we really need a named class, with a static method? • Additional conclusion: in JS you will need OOP when your program is big enough ⇒ stop worrying about the size of OOP package you use, look for completeness and correctness of its implementation.
  • 28. SI fail • Who said that a single inheritance is the only form of a relationship between classes? • Trying to use a hammer (a single inheritance) for all problems leads to poor code reuse: • Cut-and-paste code. • Duplication of methods. • Top heavy hierarchy with stubbed methods.
  • 29. SI fail • Example: • A fish, a duck, a hippo, and a submarine can swim. • Does it mean that they have a common swimming ancestor?
  • 30. Complexity fail #2 • OOP doesn't scale up. • It is not a technical limitation, it is a human limitation. • People are bad at constructing big hierarchies.
  • 31. History lessons • Plato: • Mentored by Socrates. • Mentor of Aristotle. • First major attempt to understand the classification problem in his "theory of forms".
  • 32. History lessons • Aristotle • Mentored by Plato. • Mentor of Alexander the Great. • "Corrected" Plato's theory in over 170 of his works!
  • 33. History lessons • Since 18th century numerous philosophers criticized predecessors and offered different strategies of classification. • The work is not finished yet.
  • 34. Methodology fail • So how to classify objects? How to find objects in a soup of state space? • Unless your domain has well-defined physical or logical entities, you are on your own. • Examples of well-defined objects: physical objects, graphics, UI objects, tax forms, and so on.
  • 35. What did we learn? • Like all techniques OOP has its own sweet spot/ applicability area. • It is not a universal tool. Do not abuse it. • Single inheritance is very limited. • If it doesn't fit your project, you better look for alternatives. • Keep your inheritance diagram compact.
  • 36. SI alternatives • One way to keep compact inheritance diagram is to move from a tree to a DAG: • AOP (crosscutting concerns). • Multiple inheritance (MI) (like in C++?). • Mixins (inherit from multiple bases using a DAG linearization technique). • Traits (mixin-like entities that scale up better).
  • 37. SI alternatives • Let's drop multiple inheritance. • JavaScript supports single inheritance natively, and DAG linearization would work better. • Let's drop traits. • The full machinery is too complex. • Traits rely on some static analysis, while JavaScript is essentially dynamic.
  • 38. SI augmentation: AOP • Aspect-oriented programming (AOP) requires weaving methods using three types of advices: before, after, and around. • "Before" and "after" advices are essentially chaining we already looked at before. • "Around" advice is a super call.
  • 39. SI augmentation: AOP • In order to be flexible we should support two modes of weaving: • Static (when classes are composed). • Dynamic (when objects are advised).
  • 40. SI augmentation: mixins • Mixins can inject its own state, and support its own invariants. • Mixins may participate in an object life-cycle. • Mixins can redefine existing methods, add new methods. • Mixins rely on existing methods and member variables.
  • 41. SI augmentation: mixins • Any multiple inheritance technique produces an inheritance DAG and relies on its linearization (we don't run parallel bases in parallel). • While a relative order of mixins can be specified, an absolute order is not defined. • Mixins cannot call base methods explicitly. • Implicit super calls are required.
  • 42. SI augmentation: mixins • In order to reuse JS existing single inheritance mechanisms we need to linearize an inheritance DAG. • C3 MRO (method resolution order) is the most popular and well-understood technique used in languages like Python.
  • 43. What we want • Reasonable requirements for OOP implementation so far: • Well-defined linearization (C3 MRO). • Chain constructors using "after" chaining automatically (optional). • Chain destructors using "before" chaining automatically (optional).
  • 44. What we want • Reasonable requirements for OOP implementation so far: • Anonymous/implicit super calls. • Before/after advices for methods during class composition. • Before/after/around advices for objects to weave dynamically.
  • 45. Sample implementation • New project that implements required functionality under development: dcl. • https://github.com/uhop/dcl • Runs on Node.js. • Runs with AMD-based loader (including Dojo 1.7 and RequireJS). • Can be used stand-alone in a browser.
  • 46. Sample implementation • Based on proven Dojo technologies: • The venerable dojo.declare(). • dojox/lang/aspect • dojox/lang/oo • Like Dojo licensed under BSD and AFL.
  • 47. dcl • Currently consists of three modules: • mini.js • dcl.js • advise.js
  • 48. dcl • mini.js: • Provides automatic constructor chaining out of box. • Provides implicit super calls. • For byte-conscious: just over 900 bytes.
  • 49. dcl • dcl.js: • Adds “before” and “after” weaving for class methods. • Adds after/before chaining. • Intended to be used as a main module.
  • 50. dcl • advise.js: • Provides “before”, “after”, and “around” weaving for object methods. • Advices can be removed dynamically. • That’s the main difference with dcl’s advices.
  • 51. dcl • In works: • Special debugging version of said modules. • Nobody cares about how we debug libraries. It is time we do. • Micro-library of mixins and advices including: method timer, counter, tracer, memoizer, flow analyzer, and so on.
  • 53. Picture credits Car: http://www.flickr.com/photos/arcaist/2311533441/ Car parts: http://www.flickr.com/photos/7603557@N08/2662531345/ Voronoi diagram: http://en.wikipedia.org/wiki/File:2Ddim-L2norm-10site.png Voronoi 3D: http://en.wikipedia.org/wiki/File:Coloured_Voronoi_3D_slice.png Plato: http://en.wikipedia.org/wiki/File:Plato_Silanion_Musei_Capitolini_MC1377.jpg Aristotle: http://en.wikipedia.org/wiki/File:Aristoteles_Louvre.jpg Plato & Aristotle: http://en.wikipedia.org/wiki/File:Sanzio_01_Plato_Aristotle.jpg

Notes de l'éditeur

  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
  46. \n
  47. \n
  48. \n
  49. \n
  50. \n
  51. \n
  52. \n
  53. \n