SlideShare a Scribd company logo
1 of 82
Download to read offline
Everything is Permitted:
    Extending Built-ins



                              Andrew Dupont
                          http://andrewdupont.net
Remy Sharp (flickr.com/photos/remysharp)
“ There’s a whole lot of know-nothing advocacy
  that’s still happening in the JS/webdev/design
  world these days, and it annoys me to no end.
  I’m not sure how our community got so religious
  and fact-disoriented, but it has got to stop.”
Alex Russell
“If you use this book as a guide, by all means
 leave the road when you wish. That is precisely
 the use of a road: to reach individually chosen
 points of departure. By all means break the
 rules, and break them beautifully, deliberately
 and well. That is one of the ends for which they
 exist.”
Robert Bringhurst,
The Elements of Typographic Style
“Break any of these rules sooner than say
 anything outright barbarous.”
George Orwell,
“Politics and the English Language”
“Commandments”
are no way to write code.
Alex (flickr.com/photos/littlebirdfeet/)
@DonaldGlover
      Donald Glover


Fuck what you heard, SHORTS ARE
DOPE. Just wear them right. Not mid leg
like you’re at a fuckin Creed concert.
30 Jul via Echofon
Code has social customs.
IN THE BEGINNING
    (ca. 2005)
Prototype 1.1
Object.prototype.extend = function(object) {
   for (var property in object) {
     this[property] = object[property];
   }
   return this;
};
var whiteHouse = { washington: 'adams' };
whiteHouse.extend({ adams: 'jefferson' });

for (var president in whiteHouse)
  console.log(president);
//=> washington, adams, extend
Object.prototype is verboten
http://erik.eae.net/archives/2005/06/06/22.13.54/
You can do anything you want,
  assuming it’s all your code
Object.prototype.extend
        became
    Object.extend
if (!Array.prototype.push) {
  Array.prototype.push = function() {
    var startLength = this.length;
    for (var i = 0; i < arguments.length; i++)
      this[startLength + i] = arguments[i];
    return this.length;
  };
}
Prototype 1.4 introduced
     Enumerable
for...in loops on arrays
  are usually dumb
JavaScript “Associative Arrays” Considered Harmful
               http://is.gd/js_considered_harmful
Prototype 1.5 introduced
 “Extended” elements
// Prototype 1.4
Element.addClassName('some_element', 'active');
Element.show();
$('some_element').setAttribute('title', 'Active item');

// Prototype 1.5
$('some_element').addClassName('active').show().
  setAttribute('title', 'Active item');
This was slow in IE
@kangax
      kangax


Also `typeof
document.querySelectorAll
('*').item` is 'string' in IE8. Well, that's
just silly.
16 Dec 08 via web
What’s wrong with extending the DOM
http://perfectionkills.com/whats-wrong-with-extending-the-dom/
Maintainable JavaScript: Don’t modify objects you don’t own
               http://is.gd/zakas_maintainable_javascript
Who owns built-ins?
We all do.
Social customs are a proven way
  to manage shared property.
Case in point:
   RUBY
Ruby and JavaScript
are Smalltalk-influenced
Rails gave Ruby
Active Support
ActiveSupport::CoreExtensions::Numeric
    1.day.ago
    #=> Thu Apr 21 01:57:24 -0500 2011

    (4.years + 12.days).from_now
    #=> Mon May 04 01:58:30 -0500 2015

    7.5.megabytes
    #=> 7864320.0
Symbol#to_proc


result = names.map {|name| name.upcase }
# becomes...
result = names.map(&:upcase)
http://brockman.se/2004/method-references/
Prototype 1.4
Function.prototype.bind = function() {
   var __method = this, args = $A(arguments), object = args.shift();
   return function() {
     return __method.apply(object, args.concat($A(arguments)));
   };
};
EcmaScript 5.1 Specification
Obviously,
there were fights along the way
“I only re-open a class after I’ve tried every other
 option like subclassing, wrapping, etc. If nothing else
 works or is too much effort for the modification, then
 I document the hell out of my modification and try
 desperately to localize the change so that it doesn't
 hurt anyone else.”
Zed Shaw,
“The Chainsaw Infanticide Logger Manuever”
http://is.gd/chainsaw_infanticide
“Don't slip a concrete dildo into someone's box of Fruit
 Loops. They won't be happy with your Morning
 Breakfast Surprise. Put the concrete dildo in a
 clearly labeled box, with instructions. Then when
 someone encounters a problem (‘Hey, something is
 screwing me here. Maybe it's the concrete dildo?’) at
 least they know to ask.”
The Higgs Bozo
http://is.gd/concrete_dildo
“In my mind, in Ruby < 2.0, there’s a category of library
 which is ‘provide a number of useful core
 extensions.’ The three major ones are ActiveSupport,
 Extlib and Facets. In general, applications need to
 choose one, but not more of these libraries to avoid
 conflicts.”
Yehuda Katz
http://is.gd/cQar9O
Lessons learned by Rubyists:
Make it obvious when you’re defining core extensions.
      module SomeLibrary
        module CoreExtensions
          module Object
            def foo
              # ...
            end
          end
        end
      end

      class Object
        include SomeLibrary::CoreExtensions::Object
      end
Make core extensions as atomic as possible.
require 'active_support/core_ext/numeric/bytes'

3.megabytes
#=> 3145728

3.days.ago
# NoMethodError: undefined method `days' for 3:Fixnum
If you must monkey-patch, do so seamlessly.
    Don’t break the old method’s contract.

 class Array
   alias_method :foo_original :foo

   def foo(arg)
     puts "Adding advice to the 'foo' method"
     foo_original(arg)
   end
 end
Unsolved problems:
Only one library gets the privilege
       to extend built-ins.
Libraries I require will o en decide for themselves
        which core extensions will be used.
{}.blank?
# NoMethodError: undefined method `blank?' for {}:Hash

require 'rails'
{}.blank?
#=> true
Can we extend built-ins
  safely right now?
Object.prototype.extend = function(object) {
   for (var property in object) {
     this[property] = object[property];
   }
   return this;
};
Object.prototype.extend = function(object) {
   for (var property in object) {
     this[property] = object[property];
   }
   return this;
};
ES5 to the rescue?
Object.defineProperty(Object.prototype, 'extend',
   {
     writable:     true,
     configurable: true,
     enumerable:   false,
     value: function() {
       for (var i = 0, len = arguments.length, source; i < len; i++) {
         source = arguments[i];
         for (var property in source) {
           if (source.hasOwnProperty(property))
             this[property] = source[property];
         }
       }
     }
   }
);
var whiteHouse = { washington: 'adams' };
whiteHouse.extend({ adams: 'jefferson' });

for (var president in whiteHouse)
  console.log(president);
//=> washington, adams
But wait…



var whiteHouse = { extend: 'adams' };
whiteHouse.extend({ adams: 'jefferson' });

// TypeError: Property 'extend' of object #<Object>
// is not a function
And also…




console.log(extend);
//=> [Function]
Object.prototype is still verboten
If you extend other built-ins,
consider turning off enumerability.
What about Node?
node-time
https://github.com/TooTallNate/node-time
var time = require('time');

var date = new Date();
date.setTimeZone('America/Chicago');

console.log(date.toString());
console.log(date.getTimezone());
console.log(date.getTimezoneAbbr());


Output:
Tue Apr 26 2011 02:45:21 GMT-0500 (CDT)
America/Chicago
CDT
What about the browser?
We’ll be needing ES5 polyfills
“A polyfill … is a piece of code (or plugin) that
 provides the technology that you, the
 developer, expect the browser to provide
 natively.”
 Remy Sharp
 http://remysharp.com/2010/10/08/what-is-a-polyfill/
if (!Object.keys) {
  Object.keys = function(object) {
    if (object !== Object(object))
      throw new TypeError('Object.keys called on non-object');

     var results = [];
     for (var property in object) {
       if (object.hasOwnProperty(property))
         results.push(property);
     }

      return results;
    };
}
if (!Function.prototype.bind) {
  Function.prototype.bind = function(object) {
    var slice = Array.prototype.slice,
     args = slice.call(arguments, 1),
     self = this;

      var nop     = function() {};
      var bound = function() {
        return self.apply(
           this instanceof nop ? this : (object || {}),
            args.concat(slice.call(arguments))
         );
      };

       nop.prototype   = self.prototype;
       bound.prototype = new nop();
      return bound;
    };
}
Let’s start with bind.
Prototype 1.7.1
  will have spec compliance
for all methods defined by ES5.
Will we be able to
extend built-ins safely someday?
The future:
CLASSBOXES
“[W]e present classboxes, a module system for object-
 oriented languages that allows method addition and
 replacement. Moreover, the changes made by a
 classbox are only visible to that classbox (or
 classboxes that import it), a feature we call local
 rebinding.”
So ware Composition Group,
University of Bern
http://scg.unibe.ch/research/classboxes
A classbox-like system called “refinements”
      has been proposed for Ruby 2.0.

       module TimeExtensions
         refine Numeric do
           def minutes; self * 60; end
         end
       end

       2.minutes #=> NoMethodError

       using TimeExtensions
       2.minutes #=> 120
Could we have classboxes
     in JavaScript?
Strawman: Scoped Object Extensions

module NumericExtensions {
  export extension Time = Number.prototype {
    days:    function() {},
    /* ... */

        ago:     function() {},
        fromNow: function() {}
    }
}

function setExpiringCookie(key, value) {
  import NumericExtensions.Time;
  var expires = (3).days().fromNow();
  setCookie(key, value, expires);
}

(3).days().fromNow();
//=> TypeError: Object 3 has no method 'days'
SOMEDAY
Questions?

More Related Content

What's hot

JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing UpDavid Padbury
 
Introduction to modern c++ principles(part 1)
Introduction to modern c++ principles(part 1)Introduction to modern c++ principles(part 1)
Introduction to modern c++ principles(part 1)Oky Firmansyah
 
Clojure for Java developers
Clojure for Java developersClojure for Java developers
Clojure for Java developersJohn Stevenson
 
Javascript Prototype Visualized
Javascript Prototype VisualizedJavascript Prototype Visualized
Javascript Prototype Visualized军 沈
 
Scalable JavaScript Design Patterns
Scalable JavaScript Design PatternsScalable JavaScript Design Patterns
Scalable JavaScript Design PatternsAddy Osmani
 
2012 oct-12 - java script inheritance
2012 oct-12 - java script inheritance2012 oct-12 - java script inheritance
2012 oct-12 - java script inheritancepedro.carvalho
 
Oscon Java Testing on the Fast Lane
Oscon Java Testing on the Fast LaneOscon Java Testing on the Fast Lane
Oscon Java Testing on the Fast LaneAndres Almiray
 
Ten useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesTen useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesAnkit Rastogi
 
Kotlin is charming; The reasons Java engineers should start Kotlin.
Kotlin is charming; The reasons Java engineers should start Kotlin.Kotlin is charming; The reasons Java engineers should start Kotlin.
Kotlin is charming; The reasons Java engineers should start Kotlin.JustSystems Corporation
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScriptNascenia IT
 
Advanced Object-Oriented JavaScript
Advanced Object-Oriented JavaScriptAdvanced Object-Oriented JavaScript
Advanced Object-Oriented JavaScriptecker
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced JavascriptAdieu
 
Clean code with google guava jee conf
Clean code with google guava jee confClean code with google guava jee conf
Clean code with google guava jee confIgor Anishchenko
 
5 Tips for Better JavaScript
5 Tips for Better JavaScript5 Tips for Better JavaScript
5 Tips for Better JavaScriptTodd Anglin
 
Google Guava - Core libraries for Java & Android
Google Guava - Core libraries for Java & AndroidGoogle Guava - Core libraries for Java & Android
Google Guava - Core libraries for Java & AndroidJordi Gerona
 
iPhone Seminar Part 2
iPhone Seminar Part 2iPhone Seminar Part 2
iPhone Seminar Part 2NAILBITER
 
Getting started with Clojure
Getting started with ClojureGetting started with Clojure
Getting started with ClojureJohn Stevenson
 
Real world gobbledygook
Real world gobbledygookReal world gobbledygook
Real world gobbledygookPawel Szulc
 
Awesomeness of JavaScript…almost
Awesomeness of JavaScript…almostAwesomeness of JavaScript…almost
Awesomeness of JavaScript…almostQuinton Sheppard
 

What's hot (20)

JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
Introduction to modern c++ principles(part 1)
Introduction to modern c++ principles(part 1)Introduction to modern c++ principles(part 1)
Introduction to modern c++ principles(part 1)
 
Clojure for Java developers
Clojure for Java developersClojure for Java developers
Clojure for Java developers
 
Dynamic Python
Dynamic PythonDynamic Python
Dynamic Python
 
Javascript Prototype Visualized
Javascript Prototype VisualizedJavascript Prototype Visualized
Javascript Prototype Visualized
 
Scalable JavaScript Design Patterns
Scalable JavaScript Design PatternsScalable JavaScript Design Patterns
Scalable JavaScript Design Patterns
 
2012 oct-12 - java script inheritance
2012 oct-12 - java script inheritance2012 oct-12 - java script inheritance
2012 oct-12 - java script inheritance
 
Oscon Java Testing on the Fast Lane
Oscon Java Testing on the Fast LaneOscon Java Testing on the Fast Lane
Oscon Java Testing on the Fast Lane
 
Ten useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesTen useful JavaScript tips & best practices
Ten useful JavaScript tips & best practices
 
Kotlin is charming; The reasons Java engineers should start Kotlin.
Kotlin is charming; The reasons Java engineers should start Kotlin.Kotlin is charming; The reasons Java engineers should start Kotlin.
Kotlin is charming; The reasons Java engineers should start Kotlin.
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
Advanced Object-Oriented JavaScript
Advanced Object-Oriented JavaScriptAdvanced Object-Oriented JavaScript
Advanced Object-Oriented JavaScript
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
 
Clean code with google guava jee conf
Clean code with google guava jee confClean code with google guava jee conf
Clean code with google guava jee conf
 
5 Tips for Better JavaScript
5 Tips for Better JavaScript5 Tips for Better JavaScript
5 Tips for Better JavaScript
 
Google Guava - Core libraries for Java & Android
Google Guava - Core libraries for Java & AndroidGoogle Guava - Core libraries for Java & Android
Google Guava - Core libraries for Java & Android
 
iPhone Seminar Part 2
iPhone Seminar Part 2iPhone Seminar Part 2
iPhone Seminar Part 2
 
Getting started with Clojure
Getting started with ClojureGetting started with Clojure
Getting started with Clojure
 
Real world gobbledygook
Real world gobbledygookReal world gobbledygook
Real world gobbledygook
 
Awesomeness of JavaScript…almost
Awesomeness of JavaScript…almostAwesomeness of JavaScript…almost
Awesomeness of JavaScript…almost
 

Similar to Everything is Permitted: Extending Built-ins

Spock: Test Well and Prosper
Spock: Test Well and ProsperSpock: Test Well and Prosper
Spock: Test Well and ProsperKen Kousen
 
The things we don't see – stories of Software, Scala and Akka
The things we don't see – stories of Software, Scala and AkkaThe things we don't see – stories of Software, Scala and Akka
The things we don't see – stories of Software, Scala and AkkaKonrad Malawski
 
Your Library Sucks, and why you should use it.
Your Library Sucks, and why you should use it.Your Library Sucks, and why you should use it.
Your Library Sucks, and why you should use it.Peter Higgins
 
A tour on ruby and friends
A tour on ruby and friendsA tour on ruby and friends
A tour on ruby and friends旻琦 潘
 
Exploring Clojurescript
Exploring ClojurescriptExploring Clojurescript
Exploring ClojurescriptLuke Donnet
 
Atlassian Groovy Plugins
Atlassian Groovy PluginsAtlassian Groovy Plugins
Atlassian Groovy PluginsPaul King
 
Ajax and JavaScript Bootcamp
Ajax and JavaScript BootcampAjax and JavaScript Bootcamp
Ajax and JavaScript BootcampAndreCharland
 
Lecture 03 - JQuery.pdf
Lecture 03 - JQuery.pdfLecture 03 - JQuery.pdf
Lecture 03 - JQuery.pdfLê Thưởng
 
Art of Javascript
Art of JavascriptArt of Javascript
Art of JavascriptTarek Yehia
 
Concurrent programming with Celluloid (MWRC 2012)
Concurrent programming with Celluloid (MWRC 2012)Concurrent programming with Celluloid (MWRC 2012)
Concurrent programming with Celluloid (MWRC 2012)tarcieri
 
Introduction to clojure
Introduction to clojureIntroduction to clojure
Introduction to clojureAbbas Raza
 
Maintainable JavaScript 2012
Maintainable JavaScript 2012Maintainable JavaScript 2012
Maintainable JavaScript 2012Nicholas Zakas
 
AJS UNIT-1 2021-converted.pdf
AJS UNIT-1 2021-converted.pdfAJS UNIT-1 2021-converted.pdf
AJS UNIT-1 2021-converted.pdfSreeVani74
 
Node.js Patterns for Discerning Developers
Node.js Patterns for Discerning DevelopersNode.js Patterns for Discerning Developers
Node.js Patterns for Discerning Developerscacois
 

Similar to Everything is Permitted: Extending Built-ins (20)

Spock: Test Well and Prosper
Spock: Test Well and ProsperSpock: Test Well and Prosper
Spock: Test Well and Prosper
 
The things we don't see – stories of Software, Scala and Akka
The things we don't see – stories of Software, Scala and AkkaThe things we don't see – stories of Software, Scala and Akka
The things we don't see – stories of Software, Scala and Akka
 
Your Library Sucks, and why you should use it.
Your Library Sucks, and why you should use it.Your Library Sucks, and why you should use it.
Your Library Sucks, and why you should use it.
 
"Javascript" por Tiago Rodrigues
"Javascript" por Tiago Rodrigues"Javascript" por Tiago Rodrigues
"Javascript" por Tiago Rodrigues
 
jQuery introduction
jQuery introductionjQuery introduction
jQuery introduction
 
A tour on ruby and friends
A tour on ruby and friendsA tour on ruby and friends
A tour on ruby and friends
 
Java
JavaJava
Java
 
Exploring Clojurescript
Exploring ClojurescriptExploring Clojurescript
Exploring Clojurescript
 
Atlassian Groovy Plugins
Atlassian Groovy PluginsAtlassian Groovy Plugins
Atlassian Groovy Plugins
 
Ajax and JavaScript Bootcamp
Ajax and JavaScript BootcampAjax and JavaScript Bootcamp
Ajax and JavaScript Bootcamp
 
All of javascript
All of javascriptAll of javascript
All of javascript
 
Lecture 03 - JQuery.pdf
Lecture 03 - JQuery.pdfLecture 03 - JQuery.pdf
Lecture 03 - JQuery.pdf
 
Art of Javascript
Art of JavascriptArt of Javascript
Art of Javascript
 
Concurrent programming with Celluloid (MWRC 2012)
Concurrent programming with Celluloid (MWRC 2012)Concurrent programming with Celluloid (MWRC 2012)
Concurrent programming with Celluloid (MWRC 2012)
 
Introduction to clojure
Introduction to clojureIntroduction to clojure
Introduction to clojure
 
Maintainable JavaScript 2012
Maintainable JavaScript 2012Maintainable JavaScript 2012
Maintainable JavaScript 2012
 
AJS UNIT-1 2021-converted.pdf
AJS UNIT-1 2021-converted.pdfAJS UNIT-1 2021-converted.pdf
AJS UNIT-1 2021-converted.pdf
 
All of Javascript
All of JavascriptAll of Javascript
All of Javascript
 
Node.js Patterns for Discerning Developers
Node.js Patterns for Discerning DevelopersNode.js Patterns for Discerning Developers
Node.js Patterns for Discerning Developers
 
Ruby basics
Ruby basicsRuby basics
Ruby basics
 

More from Andrew Dupont

How to Argue about Code
How to Argue about CodeHow to Argue about Code
How to Argue about CodeAndrew Dupont
 
How to Argue about JavaScript
How to Argue about JavaScriptHow to Argue about JavaScript
How to Argue about JavaScriptAndrew Dupont
 
Writing Maintainable JavaScript
Writing Maintainable JavaScriptWriting Maintainable JavaScript
Writing Maintainable JavaScriptAndrew Dupont
 
Open Government: An Overview
Open Government: An OverviewOpen Government: An Overview
Open Government: An OverviewAndrew Dupont
 
Defensive, Cross-Browser Coding with Prototype
Defensive, Cross-Browser Coding with PrototypeDefensive, Cross-Browser Coding with Prototype
Defensive, Cross-Browser Coding with PrototypeAndrew Dupont
 

More from Andrew Dupont (6)

Learning new words
Learning new wordsLearning new words
Learning new words
 
How to Argue about Code
How to Argue about CodeHow to Argue about Code
How to Argue about Code
 
How to Argue about JavaScript
How to Argue about JavaScriptHow to Argue about JavaScript
How to Argue about JavaScript
 
Writing Maintainable JavaScript
Writing Maintainable JavaScriptWriting Maintainable JavaScript
Writing Maintainable JavaScript
 
Open Government: An Overview
Open Government: An OverviewOpen Government: An Overview
Open Government: An Overview
 
Defensive, Cross-Browser Coding with Prototype
Defensive, Cross-Browser Coding with PrototypeDefensive, Cross-Browser Coding with Prototype
Defensive, Cross-Browser Coding with Prototype
 

Recently uploaded

[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...panagenda
 
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
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
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
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Scott Andery
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
(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
 
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
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 

Recently uploaded (20)

[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
 
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
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software 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
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
(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...
 
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
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 

Everything is Permitted: Extending Built-ins

  • 1. Everything is Permitted: Extending Built-ins Andrew Dupont http://andrewdupont.net
  • 3. “ There’s a whole lot of know-nothing advocacy that’s still happening in the JS/webdev/design world these days, and it annoys me to no end. I’m not sure how our community got so religious and fact-disoriented, but it has got to stop.” Alex Russell
  • 4. “If you use this book as a guide, by all means leave the road when you wish. That is precisely the use of a road: to reach individually chosen points of departure. By all means break the rules, and break them beautifully, deliberately and well. That is one of the ends for which they exist.” Robert Bringhurst, The Elements of Typographic Style
  • 5. “Break any of these rules sooner than say anything outright barbarous.” George Orwell, “Politics and the English Language”
  • 8. @DonaldGlover Donald Glover Fuck what you heard, SHORTS ARE DOPE. Just wear them right. Not mid leg like you’re at a fuckin Creed concert. 30 Jul via Echofon
  • 9. Code has social customs.
  • 10. IN THE BEGINNING (ca. 2005)
  • 12. Object.prototype.extend = function(object) { for (var property in object) { this[property] = object[property]; } return this; };
  • 13. var whiteHouse = { washington: 'adams' }; whiteHouse.extend({ adams: 'jefferson' }); for (var president in whiteHouse) console.log(president); //=> washington, adams, extend
  • 14.
  • 16.
  • 17.
  • 18. You can do anything you want, assuming it’s all your code
  • 19. Object.prototype.extend became Object.extend
  • 20. if (!Array.prototype.push) { Array.prototype.push = function() { var startLength = this.length; for (var i = 0; i < arguments.length; i++) this[startLength + i] = arguments[i]; return this.length; }; }
  • 22. for...in loops on arrays are usually dumb
  • 23. JavaScript “Associative Arrays” Considered Harmful http://is.gd/js_considered_harmful
  • 24. Prototype 1.5 introduced “Extended” elements
  • 25. // Prototype 1.4 Element.addClassName('some_element', 'active'); Element.show(); $('some_element').setAttribute('title', 'Active item'); // Prototype 1.5 $('some_element').addClassName('active').show(). setAttribute('title', 'Active item');
  • 26. This was slow in IE
  • 27. @kangax kangax Also `typeof document.querySelectorAll ('*').item` is 'string' in IE8. Well, that's just silly. 16 Dec 08 via web
  • 28. What’s wrong with extending the DOM http://perfectionkills.com/whats-wrong-with-extending-the-dom/
  • 29. Maintainable JavaScript: Don’t modify objects you don’t own http://is.gd/zakas_maintainable_javascript
  • 32. Social customs are a proven way to manage shared property.
  • 34. Ruby and JavaScript are Smalltalk-influenced
  • 36. ActiveSupport::CoreExtensions::Numeric 1.day.ago #=> Thu Apr 21 01:57:24 -0500 2011 (4.years + 12.days).from_now #=> Mon May 04 01:58:30 -0500 2015 7.5.megabytes #=> 7864320.0
  • 37. Symbol#to_proc result = names.map {|name| name.upcase } # becomes... result = names.map(&:upcase)
  • 39.
  • 40.
  • 41. Prototype 1.4 Function.prototype.bind = function() { var __method = this, args = $A(arguments), object = args.shift(); return function() { return __method.apply(object, args.concat($A(arguments))); }; };
  • 44. “I only re-open a class after I’ve tried every other option like subclassing, wrapping, etc. If nothing else works or is too much effort for the modification, then I document the hell out of my modification and try desperately to localize the change so that it doesn't hurt anyone else.” Zed Shaw, “The Chainsaw Infanticide Logger Manuever” http://is.gd/chainsaw_infanticide
  • 45. “Don't slip a concrete dildo into someone's box of Fruit Loops. They won't be happy with your Morning Breakfast Surprise. Put the concrete dildo in a clearly labeled box, with instructions. Then when someone encounters a problem (‘Hey, something is screwing me here. Maybe it's the concrete dildo?’) at least they know to ask.” The Higgs Bozo http://is.gd/concrete_dildo
  • 46. “In my mind, in Ruby < 2.0, there’s a category of library which is ‘provide a number of useful core extensions.’ The three major ones are ActiveSupport, Extlib and Facets. In general, applications need to choose one, but not more of these libraries to avoid conflicts.” Yehuda Katz http://is.gd/cQar9O
  • 47. Lessons learned by Rubyists:
  • 48. Make it obvious when you’re defining core extensions. module SomeLibrary module CoreExtensions module Object def foo # ... end end end end class Object include SomeLibrary::CoreExtensions::Object end
  • 49. Make core extensions as atomic as possible. require 'active_support/core_ext/numeric/bytes' 3.megabytes #=> 3145728 3.days.ago # NoMethodError: undefined method `days' for 3:Fixnum
  • 50. If you must monkey-patch, do so seamlessly. Don’t break the old method’s contract. class Array alias_method :foo_original :foo def foo(arg) puts "Adding advice to the 'foo' method" foo_original(arg) end end
  • 52. Only one library gets the privilege to extend built-ins.
  • 53. Libraries I require will o en decide for themselves which core extensions will be used. {}.blank? # NoMethodError: undefined method `blank?' for {}:Hash require 'rails' {}.blank? #=> true
  • 54. Can we extend built-ins safely right now?
  • 55. Object.prototype.extend = function(object) { for (var property in object) { this[property] = object[property]; } return this; };
  • 56. Object.prototype.extend = function(object) { for (var property in object) { this[property] = object[property]; } return this; };
  • 57. ES5 to the rescue? Object.defineProperty(Object.prototype, 'extend', { writable: true, configurable: true, enumerable: false, value: function() { for (var i = 0, len = arguments.length, source; i < len; i++) { source = arguments[i]; for (var property in source) { if (source.hasOwnProperty(property)) this[property] = source[property]; } } } } );
  • 58. var whiteHouse = { washington: 'adams' }; whiteHouse.extend({ adams: 'jefferson' }); for (var president in whiteHouse) console.log(president); //=> washington, adams
  • 59.
  • 60. But wait… var whiteHouse = { extend: 'adams' }; whiteHouse.extend({ adams: 'jefferson' }); // TypeError: Property 'extend' of object #<Object> // is not a function
  • 61.
  • 63.
  • 65. If you extend other built-ins, consider turning off enumerability.
  • 68. var time = require('time'); var date = new Date(); date.setTimeZone('America/Chicago'); console.log(date.toString()); console.log(date.getTimezone()); console.log(date.getTimezoneAbbr()); Output: Tue Apr 26 2011 02:45:21 GMT-0500 (CDT) America/Chicago CDT
  • 69. What about the browser?
  • 70. We’ll be needing ES5 polyfills “A polyfill … is a piece of code (or plugin) that provides the technology that you, the developer, expect the browser to provide natively.” Remy Sharp http://remysharp.com/2010/10/08/what-is-a-polyfill/
  • 71. if (!Object.keys) { Object.keys = function(object) { if (object !== Object(object)) throw new TypeError('Object.keys called on non-object'); var results = []; for (var property in object) { if (object.hasOwnProperty(property)) results.push(property); } return results; }; }
  • 72. if (!Function.prototype.bind) { Function.prototype.bind = function(object) { var slice = Array.prototype.slice, args = slice.call(arguments, 1), self = this; var nop = function() {}; var bound = function() { return self.apply( this instanceof nop ? this : (object || {}), args.concat(slice.call(arguments)) ); }; nop.prototype = self.prototype; bound.prototype = new nop(); return bound; }; }
  • 74. Prototype 1.7.1 will have spec compliance for all methods defined by ES5.
  • 75. Will we be able to extend built-ins safely someday?
  • 77. “[W]e present classboxes, a module system for object- oriented languages that allows method addition and replacement. Moreover, the changes made by a classbox are only visible to that classbox (or classboxes that import it), a feature we call local rebinding.” So ware Composition Group, University of Bern http://scg.unibe.ch/research/classboxes
  • 78. A classbox-like system called “refinements” has been proposed for Ruby 2.0. module TimeExtensions refine Numeric do def minutes; self * 60; end end end 2.minutes #=> NoMethodError using TimeExtensions 2.minutes #=> 120
  • 79. Could we have classboxes in JavaScript?
  • 80. Strawman: Scoped Object Extensions module NumericExtensions { export extension Time = Number.prototype { days: function() {}, /* ... */ ago: function() {}, fromNow: function() {} } } function setExpiringCookie(key, value) { import NumericExtensions.Time; var expires = (3).days().fromNow(); setCookie(key, value, expires); } (3).days().fromNow(); //=> TypeError: Object 3 has no method 'days'