SlideShare a Scribd company logo
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 developers
John 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 Patterns
Addy 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 Lane
Andres Almiray
 
Ten useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesTen useful JavaScript tips & best practices
Ten useful JavaScript tips & best practices
Ankit 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 JavaScript
Nascenia IT
 
Advanced Object-Oriented JavaScript
Advanced Object-Oriented JavaScriptAdvanced Object-Oriented JavaScript
Advanced Object-Oriented JavaScript
ecker
 
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 conf
Igor Anishchenko
 
5 Tips for Better JavaScript
5 Tips for Better JavaScript5 Tips for Better JavaScript
5 Tips for Better JavaScript
Todd 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 & Android
Jordi Gerona
 
iPhone Seminar Part 2
iPhone Seminar Part 2iPhone Seminar Part 2
iPhone Seminar Part 2
NAILBITER
 
Getting started with Clojure
Getting started with ClojureGetting started with Clojure
Getting started with Clojure
John Stevenson
 
Real world gobbledygook
Real world gobbledygookReal world gobbledygook
Real world gobbledygook
Pawel Szulc
 
Awesomeness of JavaScript…almost
Awesomeness of JavaScript…almostAwesomeness of JavaScript…almost
Awesomeness of JavaScript…almost
Quinton 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 Prosper
Ken 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 Akka
Konrad 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
 
"Javascript" por Tiago Rodrigues
"Javascript" por Tiago Rodrigues"Javascript" por Tiago Rodrigues
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 Clojurescript
Luke Donnet
 
Atlassian Groovy Plugins
Atlassian Groovy PluginsAtlassian Groovy Plugins
Atlassian Groovy Plugins
Paul King
 
Ajax and JavaScript Bootcamp
Ajax and JavaScript BootcampAjax and JavaScript Bootcamp
Ajax and JavaScript Bootcamp
AndreCharland
 
Lecture 03 - JQuery.pdf
Lecture 03 - JQuery.pdfLecture 03 - JQuery.pdf
Lecture 03 - JQuery.pdf
Lê Thưởng
 
Art of Javascript
Art of JavascriptArt of Javascript
Art of Javascript
Tarek 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 clojure
Abbas Raza
 
Maintainable JavaScript 2012
Maintainable JavaScript 2012Maintainable JavaScript 2012
Maintainable JavaScript 2012
Nicholas Zakas
 
AJS UNIT-1 2021-converted.pdf
AJS UNIT-1 2021-converted.pdfAJS UNIT-1 2021-converted.pdf
AJS UNIT-1 2021-converted.pdf
SreeVani74
 
Node.js Patterns for Discerning Developers
Node.js Patterns for Discerning DevelopersNode.js Patterns for Discerning Developers
Node.js Patterns for Discerning Developers
cacois
 
Ruby basics
Ruby basicsRuby basics
Ruby basics
Aditya Tiwari
 

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

Learning new words
Learning new wordsLearning new words
Learning new words
Andrew Dupont
 
How to Argue about Code
How to Argue about CodeHow to Argue about Code
How to Argue about Code
Andrew Dupont
 
How to Argue about JavaScript
How to Argue about JavaScriptHow to Argue about JavaScript
How to Argue about JavaScript
Andrew Dupont
 
Writing Maintainable JavaScript
Writing Maintainable JavaScriptWriting Maintainable JavaScript
Writing Maintainable JavaScript
Andrew Dupont
 
Open Government: An Overview
Open Government: An OverviewOpen Government: An Overview
Open Government: An Overview
Andrew Dupont
 
Defensive, Cross-Browser Coding with Prototype
Defensive, Cross-Browser Coding with PrototypeDefensive, Cross-Browser Coding with Prototype
Defensive, Cross-Browser Coding with Prototype
Andrew 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

How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
Abida Shariff
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
Bhaskar Mitra
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
Fwdays
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 

Recently uploaded (20)

How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 

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'