SlideShare uma empresa Scribd logo
1 de 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

Mais conteúdo relacionado

Mais procurados

Intro to java programming
Intro to java programmingIntro to java programming
Intro to java programming
Leah Stephens
 
Ontology Engineering: ontology construction II
Ontology Engineering: ontology construction IIOntology Engineering: ontology construction II
Ontology Engineering: ontology construction II
Guus Schreiber
 
GeekAustin PHP Class - Session 6
GeekAustin PHP Class - Session 6GeekAustin PHP Class - Session 6
GeekAustin PHP Class - Session 6
jimbojsb
 
Deploying Rails Applications: Lessons Learned
Deploying Rails Applications: Lessons LearnedDeploying Rails Applications: Lessons Learned
Deploying Rails Applications: Lessons Learned
Michael Koby
 

Mais procurados (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
 

Destaque

Destaque (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
 

Semelhante a OOP in JS

Orthogonality: A Strategy for Reusable Code
Orthogonality: A Strategy for Reusable CodeOrthogonality: A Strategy for Reusable Code
Orthogonality: A Strategy for Reusable Code
rsebbe
 

Semelhante a 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
 
Object Oriented Programming Tutorial.pptx
Object Oriented Programming Tutorial.pptxObject Oriented Programming Tutorial.pptx
Object Oriented Programming Tutorial.pptx
 
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
 

Mais de Eugene Lazutkin

Mais 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
 

Último

Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 

Último (20)

Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 

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

Notas do Editor

  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