SlideShare a Scribd company logo
1 of 30
Download to read offline
WHY NESTED
TERNARY OPERATORS
MAKE ME WANT TO
KICK INANIMATE
OBJECTS IN THE NUTS
AKA: Making JavaScript Libraries More Approachable




       http://tinyurl.com/ternaryops


                                                     Pamela Fox
                                                     @pamelafox
IN THE WORLD OF JS LIBRARIES...
 



                    AUTHORS
       USERS
I'VE BEEN USING A LOT OF LIBRARIES
THIS PAST YEAR...

 bootstrap.datepicker.js   jquery-1.7.min.js       jsrender.js
 bootstrap.js              jquery.autosuggest.js   lscache.js
 colorslider.js            jquery.calendrical.js   modernizr-1.7.js
 confetti.js               jquery.dateinput.js     personalize.js
 date.format.js            jquery.fancybox.js      phonegap.js
 dateinput.js              jquery.mobile.js        stacktrace.js
 dd_belatedpng.js          jquery.overlay.js       throttle.js
 facebook.js               jquery.sparkline.js     timeago.js
 facebook_js_sdk.js        jquery.tablesorter.js   useragent.js
 handlebars.js             jquery.tagfield.js      zepto.js
 highcharts.js             jquery.tooltip.js
AND SOMETIMES I SEE STUFF LIKE...
 
(aposed
      ? (aposed = !apos, (aposed ? all : '"'))
      : quoted
            ? (quoted = !quot, (quoted ? all : '"'))
            :
      (
            (lftPrn
                  ? (parenDepth++, lftPrn)
                  : "")
            + (space
                  ? (parenDepth
                               ? ""
                               : named
                                            ? (named = FALSE, "b")
                                            : ","
                  )
                  : eq
                        ? (parenDepth && syntaxError(), named = TRUE, 'b' + path + ':')
                        : path
                               ? (path.replace( rPath, parsePath )
                                     + (prn
                                            ? (fnCall[ ++parenDepth ] = TRUE, prn)
                                            : operator)
                               )
                               : operator
                                     ? all
                                     : rtPrn
                                            ? ((fnCall[ parenDepth-- ] = FALSE, rtPrn)
                                                  + (prn
                                                         ? (fnCall[ ++parenDepth ] = TRUE, prn)
                                                         : "")
                                            )
                                            : comma
                                                  ? (fnCall[ parenDepth ] || syntaxError(), ",")
                                                  : lftPrn0
                                                         ? ""
                                                         : (aposed = apos, quoted = quot, '"')
))
AND IT MAKES ME THINK OF....
 
...WOULDN'T THIS BE BETTER?
 
THE STAGES OF BEING A USER:
 
 
  1. Learn how a library works & start using it.
    
  2. Debug a library when something goes wrong.
    
  3. Integrate a library with their workflow.
    
  4. BONUS: Submit a patch to the library.
STEP 1: THIS LOOKS LIKE A USEFUL
LIBRARY, LET'S SEE HOW TO USE IT.
    Document everything.
 
      JSDoc, JSDuck, JoDoc, Dox, NDoc,
      Docco, Docco-Husky,
      AutoObjectDocumentation
 
    Make the documentation easy to patch.
 
NOT ENOUGH DOCUMENTATION.
 
this.options.knownHelpers = {
    'each': true,
    'if': true,
    'unless': true,
    'with': true,
    'log': true
};
                handlebars.js
TOO MUCH DOCUMENTATION.
 



                              vs.




   http://handlebarsjs.com/         https://github.com/wycats/handlebars.js/
DUPLICATE DOCUMENTATION.
 



             vs.
STEP 2: UH OH, SOMETHING WENT
WRONG. TIME TO DEBUG THE LIB.
Make your code readable.
 ○ "Common conventions"
   ■ Idiomatic.js
   ■ Crockford
   ■ Google
   ■ Stoyan Stefanov
 ○ Descriptive variable names


 Make your code debuggable.
 ○ On *all* platforms.
SHORTENED VARIABLE NAMES.
 ar a = s.split("."),
v
        r = "",
        l = a.length;
for (var i = 0; i < l; i++) {
  var item = a[i];
  if (item.length == 2) {
    r += "0" + item;
  } else {
    r += item;
  }
}


function login(a, b) {
    b = b || { perms: '' };
    PhoneGap.exec(function(e) {
      FB.Auth.setSession(e.session, 'connected');
      if (a) a(e);
     }, null, 'com.phonegap.facebook.Connect', 'login', b.
perms.split(',') );
}
SHORTENED VARIABLE NAMES.
 
 FOR:
   The shortened names make sense.
  
 AGAINST:
   Maybe to you. But not to people new to the
 code.
  
   "Common sense" is not common.
SHORTENED VARIABLE NAMES.
 
 FOR:
   It makes for less bytes of code.
  
 AGAINST:
   Code will get compiled to least number of
 bytes anyway.
  
SHORTENED VARIABLE NAMES.
 
 FOR:
   It makes for shorter lines of code.
  
 AGAINST:
   Readability trumps line length.
  
MISSING SEMI-COLONS.
 
MISSING SEMI-COLONS.
 
 AGAINST:
   It's harder to read the code.
  
  "Readability is the single most important quality of a
 piece of code. Semicolons aid readability by eliminating
 ambiguity and ensuring that nobody ever has to spend
 even a second figuring out whether your code will do
 what it looks like it will do."
                                            Jason Kester


 "Relying on implicit insertion can cause subtle, hard to
 debug problems. Don't do it. You're better than that."
                                            Google Style Guide
MISSING SEMI-COLONS.
 
 AGAINST:
  It's harder to make non-breaking changes
 to the code.
 this:

  a = b + c
  (d + e).print()

 is interpreted as:


  a = b + c(d + e).print();

 so you have to:

  ;(d + e).print()
MISSING SEMI-COLONS.
 
 FOR:
   It's what the core team prefers.
  
 AGAINST:
   The core team aren't the only developers
 looking at the code. (But they might be if
 that's the philosophy.)

 Don't use your library code to show off how well you
 know the idiosyncrasies of a language.
MISSING SEMI-COLONS.
 
 AGAINST:
  Hacker News agrees.
NESTED TERNARY OPERATORS.
 
$.qsa = $$ = function(element, selector){
    var found
    return (element === document && idSelectorRE.test(selector)) ?
      ( (found = element.getElementById(RegExp.$1)) ? [found] : emptyArray )
:
      (element.nodeType !== 1 && element.nodeType !== 9) ? emptyArray :
      slice.call(
        classSelectorRE.test(selector) ? element.getElementsByClassName
(RegExp.$1) :
        tagSelectorRE.test(selector) ? element.getElementsByTagName
(selector) :
        element.querySelectorAll(selector)
      )
  }
                               zepto.js
NESTED TERNARY OPERATORS.
 AGAINST:
    They're hard to understand.
 $.qsa = $$ = function(element, selector){
    var found;
    if (element === document && idSelectorRE.test(selector)) {
      found = element.getElementById(RegExp.$1);
      return found && [found] || [];
    } else if (classSelectorRE.test(selector)) {
      return slice.call(element.getElementsByClassName(RegExp.$1));
    } else if (tagSelectorRE.test(selector)) {
      return slice.call(element.getElementsByTagName(selector));
    } else {
      return slice.call(attemptQuerySelectorAll(element, selector));
    }
}




If you have the choice between two styles and
one is more readable, choose that one.
NESTED TERNARY OPERATORS.
 
 AGAINST:
   It's hard to debug the nested statements.
  
 FOR:
   You can debug them with breakpoints.
  
 AGAINST:
    You can't always use fancy debuggers.
     See: Android, IE
NESTED TERNARY OPERATORS.
 
FOR:
  They perform better than if/else.
 
AGAINST:
   Compilers convert if/else to ternary.
   Try in UglifyJS or Closure Compiler.
STEP 3: OK, ALL WORKING. TIME TO
INTEGRATE WITH MY WORKFLOW.
Try your code with popular JS build tools
  ● JSHint
  ● Closure Compiler / UglifyJS
  ● Grunt
 
   If it requires options, specify them or inline
them into the code.
UNSPECIFIED JSHINT OPTIONS.
 
[jshint] Error(s) in ./application/static/js/libs/bootstrap.js:
Missing semicolon. (line: 24, character: 5)
> "use strict"

Comma warnings can be turned off with 'laxcomma' (line: 31, character: 9)
> , thisStyle = thisBody.style

Bad line breaking before ','. (line: 30, character: 48)
> var thisBody = document.body || document.documentElement

...
Too many errors. (8% scanned). (line: 139, character: 73)




/*jshint asi:true, laxbreak:true, laxcomma:true, expr:true, boss:true */
STEP 4: WHEE, IT WORKS, NOW I JUST
WANNA SUBMIT THIS ONE CHANGE.

Make it easy to build.
 
Make the tests easy to run.
 
 ...use familiar tools and languages.
TOO MANY TOOLS?
 
SO, IF YOU'RE A LIBRARY...

WHICH ONE DO YOU WANT TO BE?
            elite                      approachable




                              vs.




                    AUTHORS
         USERS                      USERS       AUTHORS

More Related Content

What's hot

Adding 1.21 Gigawatts to Applications with RabbitMQ (PHP Oxford June Meetup 2...
Adding 1.21 Gigawatts to Applications with RabbitMQ (PHP Oxford June Meetup 2...Adding 1.21 Gigawatts to Applications with RabbitMQ (PHP Oxford June Meetup 2...
Adding 1.21 Gigawatts to Applications with RabbitMQ (PHP Oxford June Meetup 2...James Titcumb
 
Code obfuscation, php shells & more
Code obfuscation, php shells & moreCode obfuscation, php shells & more
Code obfuscation, php shells & moreMattias Geniar
 
Web Scraper Shibuya.pm tech talk #8
Web Scraper Shibuya.pm tech talk #8Web Scraper Shibuya.pm tech talk #8
Web Scraper Shibuya.pm tech talk #8Tatsuhiko Miyagawa
 
Arduino programming of ML-style in ATS
Arduino programming of ML-style in ATSArduino programming of ML-style in ATS
Arduino programming of ML-style in ATSKiwamu Okabe
 
Top 10 php classic traps DPC 2020
Top 10 php classic traps DPC 2020Top 10 php classic traps DPC 2020
Top 10 php classic traps DPC 2020Damien Seguy
 
Using DAOs without implementing them
Using DAOs without implementing themUsing DAOs without implementing them
Using DAOs without implementing thembenfante
 
Functional Programming & Event Sourcing - a pair made in heaven
Functional Programming & Event Sourcing - a pair made in heavenFunctional Programming & Event Sourcing - a pair made in heaven
Functional Programming & Event Sourcing - a pair made in heavenPawel Szulc
 
Monads asking the right question
Monads  asking the right questionMonads  asking the right question
Monads asking the right questionPawel Szulc
 
Unit testing like a pirate #wceu 2013
Unit testing like a pirate #wceu 2013Unit testing like a pirate #wceu 2013
Unit testing like a pirate #wceu 2013Ptah Dunbar
 
JavaScript - Like a Box of Chocolates
JavaScript - Like a Box of ChocolatesJavaScript - Like a Box of Chocolates
JavaScript - Like a Box of ChocolatesRobert Nyman
 
Good practices for PrestaShop code security and optimization
Good practices for PrestaShop code security and optimizationGood practices for PrestaShop code security and optimization
Good practices for PrestaShop code security and optimizationPrestaShop
 
FizzBuzzではじめるテスト
FizzBuzzではじめるテストFizzBuzzではじめるテスト
FizzBuzzではじめるテストMasashi Shinbara
 
Evolving Software with Moose
Evolving Software with MooseEvolving Software with Moose
Evolving Software with MooseDave Cross
 
PHP Doesn't Suck
PHP Doesn't SuckPHP Doesn't Suck
PHP Doesn't SuckJohn Hobbs
 

What's hot (20)

Adding 1.21 Gigawatts to Applications with RabbitMQ (PHP Oxford June Meetup 2...
Adding 1.21 Gigawatts to Applications with RabbitMQ (PHP Oxford June Meetup 2...Adding 1.21 Gigawatts to Applications with RabbitMQ (PHP Oxford June Meetup 2...
Adding 1.21 Gigawatts to Applications with RabbitMQ (PHP Oxford June Meetup 2...
 
Getting Testy With Perl6
Getting Testy With Perl6Getting Testy With Perl6
Getting Testy With Perl6
 
Code obfuscation, php shells & more
Code obfuscation, php shells & moreCode obfuscation, php shells & more
Code obfuscation, php shells & more
 
Web Scraper Shibuya.pm tech talk #8
Web Scraper Shibuya.pm tech talk #8Web Scraper Shibuya.pm tech talk #8
Web Scraper Shibuya.pm tech talk #8
 
Arduino programming of ML-style in ATS
Arduino programming of ML-style in ATSArduino programming of ML-style in ATS
Arduino programming of ML-style in ATS
 
Top 10 php classic traps DPC 2020
Top 10 php classic traps DPC 2020Top 10 php classic traps DPC 2020
Top 10 php classic traps DPC 2020
 
Smoking docker
Smoking dockerSmoking docker
Smoking docker
 
Using DAOs without implementing them
Using DAOs without implementing themUsing DAOs without implementing them
Using DAOs without implementing them
 
Functional Programming & Event Sourcing - a pair made in heaven
Functional Programming & Event Sourcing - a pair made in heavenFunctional Programming & Event Sourcing - a pair made in heaven
Functional Programming & Event Sourcing - a pair made in heaven
 
Monads asking the right question
Monads  asking the right questionMonads  asking the right question
Monads asking the right question
 
Unit testing like a pirate #wceu 2013
Unit testing like a pirate #wceu 2013Unit testing like a pirate #wceu 2013
Unit testing like a pirate #wceu 2013
 
Modern Perl
Modern PerlModern Perl
Modern Perl
 
JavaScript - Like a Box of Chocolates
JavaScript - Like a Box of ChocolatesJavaScript - Like a Box of Chocolates
JavaScript - Like a Box of Chocolates
 
Good practices for PrestaShop code security and optimization
Good practices for PrestaShop code security and optimizationGood practices for PrestaShop code security and optimization
Good practices for PrestaShop code security and optimization
 
Lettering js
Lettering jsLettering js
Lettering js
 
FizzBuzzではじめるテスト
FizzBuzzではじめるテストFizzBuzzではじめるテスト
FizzBuzzではじめるテスト
 
Evolving Software with Moose
Evolving Software with MooseEvolving Software with Moose
Evolving Software with Moose
 
Fantom and Tales
Fantom and TalesFantom and Tales
Fantom and Tales
 
Yahoo is open to developers
Yahoo is open to developersYahoo is open to developers
Yahoo is open to developers
 
PHP Doesn't Suck
PHP Doesn't SuckPHP Doesn't Suck
PHP Doesn't Suck
 

Viewers also liked

No, Really, I'm Shy
No, Really, I'm ShyNo, Really, I'm Shy
No, Really, I'm ShyPamela Fox
 
A Year of Hermit Hacking
A Year of Hermit HackingA Year of Hermit Hacking
A Year of Hermit HackingPamela Fox
 
Living in the Cloud: Hosting Data & Apps Using the Google Infrastructure
Living in the Cloud: Hosting Data & Apps Using the Google InfrastructureLiving in the Cloud: Hosting Data & Apps Using the Google Infrastructure
Living in the Cloud: Hosting Data & Apps Using the Google InfrastructurePamela Fox
 
Growing up Geek: My Dad, the Computer Scientist
Growing up Geek: My Dad, the Computer ScientistGrowing up Geek: My Dad, the Computer Scientist
Growing up Geek: My Dad, the Computer ScientistPamela Fox
 
Web APIs & Google APIs
Web APIs & Google APIsWeb APIs & Google APIs
Web APIs & Google APIsPamela Fox
 
The Wonders of the "Onesie"
The Wonders of the "Onesie"The Wonders of the "Onesie"
The Wonders of the "Onesie"Pamela Fox
 
Client Killed the Server Star
Client Killed the Server StarClient Killed the Server Star
Client Killed the Server StarPamela Fox
 
Django Admin: Widgetry & Witchery
Django Admin: Widgetry & WitcheryDjango Admin: Widgetry & Witchery
Django Admin: Widgetry & WitcheryPamela Fox
 
Engineering culture
Engineering cultureEngineering culture
Engineering culturePamela Fox
 

Viewers also liked (9)

No, Really, I'm Shy
No, Really, I'm ShyNo, Really, I'm Shy
No, Really, I'm Shy
 
A Year of Hermit Hacking
A Year of Hermit HackingA Year of Hermit Hacking
A Year of Hermit Hacking
 
Living in the Cloud: Hosting Data & Apps Using the Google Infrastructure
Living in the Cloud: Hosting Data & Apps Using the Google InfrastructureLiving in the Cloud: Hosting Data & Apps Using the Google Infrastructure
Living in the Cloud: Hosting Data & Apps Using the Google Infrastructure
 
Growing up Geek: My Dad, the Computer Scientist
Growing up Geek: My Dad, the Computer ScientistGrowing up Geek: My Dad, the Computer Scientist
Growing up Geek: My Dad, the Computer Scientist
 
Web APIs & Google APIs
Web APIs & Google APIsWeb APIs & Google APIs
Web APIs & Google APIs
 
The Wonders of the "Onesie"
The Wonders of the "Onesie"The Wonders of the "Onesie"
The Wonders of the "Onesie"
 
Client Killed the Server Star
Client Killed the Server StarClient Killed the Server Star
Client Killed the Server Star
 
Django Admin: Widgetry & Witchery
Django Admin: Widgetry & WitcheryDjango Admin: Widgetry & Witchery
Django Admin: Widgetry & Witchery
 
Engineering culture
Engineering cultureEngineering culture
Engineering culture
 

Similar to Making JavaScript Libraries More Approachable

Extreme Swift
Extreme SwiftExtreme Swift
Extreme SwiftMovel
 
Real life-coffeescript
Real life-coffeescriptReal life-coffeescript
Real life-coffeescriptDavid Furber
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side JavascriptJulie Iskander
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming iiPrashant Kalkar
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)Pavlo Baron
 
name name2 n
name name2 nname name2 n
name name2 ncallroom
 
name name2 n2.ppt
name name2 n2.pptname name2 n2.ppt
name name2 n2.pptcallroom
 
Ruby for Perl Programmers
Ruby for Perl ProgrammersRuby for Perl Programmers
Ruby for Perl Programmersamiable_indian
 
name name2 n2
name name2 n2name name2 n2
name name2 n2callroom
 

Similar to Making JavaScript Libraries More Approachable (20)

Extreme Swift
Extreme SwiftExtreme Swift
Extreme Swift
 
Txjs
TxjsTxjs
Txjs
 
lab4_php
lab4_phplab4_php
lab4_php
 
lab4_php
lab4_phplab4_php
lab4_php
 
Real life-coffeescript
Real life-coffeescriptReal life-coffeescript
Real life-coffeescript
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming ii
 
SDC - Einführung in Scala
SDC - Einführung in ScalaSDC - Einführung in Scala
SDC - Einführung in Scala
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)
 
Python basic
Python basicPython basic
Python basic
 
ppt7
ppt7ppt7
ppt7
 
ppt2
ppt2ppt2
ppt2
 
name name2 n
name name2 nname name2 n
name name2 n
 
test ppt
test ppttest ppt
test ppt
 
ppt30
ppt30ppt30
ppt30
 
name name2 n2.ppt
name name2 n2.pptname name2 n2.ppt
name name2 n2.ppt
 
ppt18
ppt18ppt18
ppt18
 
Ruby for Perl Programmers
Ruby for Perl ProgrammersRuby for Perl Programmers
Ruby for Perl Programmers
 
ppt9
ppt9ppt9
ppt9
 
name name2 n2
name name2 n2name name2 n2
name name2 n2
 

More from Pamela Fox

The Developer Experience
The Developer Experience The Developer Experience
The Developer Experience Pamela Fox
 
How I became a born again vegetable-tarian
How I became a born again vegetable-tarianHow I became a born again vegetable-tarian
How I became a born again vegetable-tarianPamela Fox
 
The Developer Experience
The Developer ExperienceThe Developer Experience
The Developer ExperiencePamela Fox
 
Writing Apps the Google-y Way (Brisbane)
Writing Apps the Google-y Way (Brisbane)Writing Apps the Google-y Way (Brisbane)
Writing Apps the Google-y Way (Brisbane)Pamela Fox
 
Writing Apps the Google-y Way
Writing Apps the Google-y WayWriting Apps the Google-y Way
Writing Apps the Google-y WayPamela Fox
 
I’M A Barbie Girl In A CS World
I’M A Barbie Girl In A CS WorldI’M A Barbie Girl In A CS World
I’M A Barbie Girl In A CS WorldPamela Fox
 
Google Wave 20/20: Product, Protocol, Platform
Google Wave 20/20: Product, Protocol, PlatformGoogle Wave 20/20: Product, Protocol, Platform
Google Wave 20/20: Product, Protocol, PlatformPamela Fox
 
Collaborative Mapping with Google Wave
Collaborative Mapping with Google WaveCollaborative Mapping with Google Wave
Collaborative Mapping with Google WavePamela Fox
 
Google Products: Deep Dive on Google Maps
Google Products: Deep Dive on Google MapsGoogle Products: Deep Dive on Google Maps
Google Products: Deep Dive on Google MapsPamela Fox
 
Google Products & Google Maps
Google Products & Google MapsGoogle Products & Google Maps
Google Products & Google MapsPamela Fox
 
Mashups & APIs
Mashups & APIsMashups & APIs
Mashups & APIsPamela Fox
 
A World of Words
A World of WordsA World of Words
A World of WordsPamela Fox
 
Flex vs. HTML5 for RIAS
Flex vs. HTML5 for RIASFlex vs. HTML5 for RIAS
Flex vs. HTML5 for RIASPamela Fox
 
NORAD Santa Tracker: Tips & Tricks
NORAD Santa Tracker: Tips & TricksNORAD Santa Tracker: Tips & Tricks
NORAD Santa Tracker: Tips & TricksPamela Fox
 
OpenSocial Intro
OpenSocial IntroOpenSocial Intro
OpenSocial IntroPamela Fox
 
Socializing Apps
Socializing AppsSocializing Apps
Socializing AppsPamela Fox
 
Open Maps (Or Close Enough?)
Open Maps (Or Close Enough?)Open Maps (Or Close Enough?)
Open Maps (Or Close Enough?)Pamela Fox
 
Gadgets Intro (Plus Mapplets)
Gadgets Intro (Plus Mapplets)Gadgets Intro (Plus Mapplets)
Gadgets Intro (Plus Mapplets)Pamela Fox
 
Data-Driven Facial Animation Based on Feature Points
Data-Driven Facial Animation Based on Feature Points Data-Driven Facial Animation Based on Feature Points
Data-Driven Facial Animation Based on Feature Points Pamela Fox
 
Feature-based laser data simplification for low polygon visualization
 Feature-based laser data simplification for low polygon visualization Feature-based laser data simplification for low polygon visualization
Feature-based laser data simplification for low polygon visualizationPamela Fox
 

More from Pamela Fox (20)

The Developer Experience
The Developer Experience The Developer Experience
The Developer Experience
 
How I became a born again vegetable-tarian
How I became a born again vegetable-tarianHow I became a born again vegetable-tarian
How I became a born again vegetable-tarian
 
The Developer Experience
The Developer ExperienceThe Developer Experience
The Developer Experience
 
Writing Apps the Google-y Way (Brisbane)
Writing Apps the Google-y Way (Brisbane)Writing Apps the Google-y Way (Brisbane)
Writing Apps the Google-y Way (Brisbane)
 
Writing Apps the Google-y Way
Writing Apps the Google-y WayWriting Apps the Google-y Way
Writing Apps the Google-y Way
 
I’M A Barbie Girl In A CS World
I’M A Barbie Girl In A CS WorldI’M A Barbie Girl In A CS World
I’M A Barbie Girl In A CS World
 
Google Wave 20/20: Product, Protocol, Platform
Google Wave 20/20: Product, Protocol, PlatformGoogle Wave 20/20: Product, Protocol, Platform
Google Wave 20/20: Product, Protocol, Platform
 
Collaborative Mapping with Google Wave
Collaborative Mapping with Google WaveCollaborative Mapping with Google Wave
Collaborative Mapping with Google Wave
 
Google Products: Deep Dive on Google Maps
Google Products: Deep Dive on Google MapsGoogle Products: Deep Dive on Google Maps
Google Products: Deep Dive on Google Maps
 
Google Products & Google Maps
Google Products & Google MapsGoogle Products & Google Maps
Google Products & Google Maps
 
Mashups & APIs
Mashups & APIsMashups & APIs
Mashups & APIs
 
A World of Words
A World of WordsA World of Words
A World of Words
 
Flex vs. HTML5 for RIAS
Flex vs. HTML5 for RIASFlex vs. HTML5 for RIAS
Flex vs. HTML5 for RIAS
 
NORAD Santa Tracker: Tips & Tricks
NORAD Santa Tracker: Tips & TricksNORAD Santa Tracker: Tips & Tricks
NORAD Santa Tracker: Tips & Tricks
 
OpenSocial Intro
OpenSocial IntroOpenSocial Intro
OpenSocial Intro
 
Socializing Apps
Socializing AppsSocializing Apps
Socializing Apps
 
Open Maps (Or Close Enough?)
Open Maps (Or Close Enough?)Open Maps (Or Close Enough?)
Open Maps (Or Close Enough?)
 
Gadgets Intro (Plus Mapplets)
Gadgets Intro (Plus Mapplets)Gadgets Intro (Plus Mapplets)
Gadgets Intro (Plus Mapplets)
 
Data-Driven Facial Animation Based on Feature Points
Data-Driven Facial Animation Based on Feature Points Data-Driven Facial Animation Based on Feature Points
Data-Driven Facial Animation Based on Feature Points
 
Feature-based laser data simplification for low polygon visualization
 Feature-based laser data simplification for low polygon visualization Feature-based laser data simplification for low polygon visualization
Feature-based laser data simplification for low polygon visualization
 

Recently uploaded

COMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a WebsiteCOMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a Websitedgelyza
 
UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1DianaGray10
 
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCostKubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCostMatt Ray
 
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAAnypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAshyamraj55
 
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDEADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDELiveplex
 
Videogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfVideogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfinfogdgmi
 
Building AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptxBuilding AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptxUdaiappa Ramachandran
 
9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding TeamAdam Moalla
 
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesAI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesMd Hossain Ali
 
UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8DianaGray10
 
Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Adtran
 
UiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation DevelopersUiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation DevelopersUiPathCommunity
 
Machine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfMachine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfAijun Zhang
 
Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.YounusS2
 
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve DecarbonizationUsing IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve DecarbonizationIES VE
 
Bird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemBird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemAsko Soukka
 
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfJamie (Taka) Wang
 

Recently uploaded (20)

COMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a WebsiteCOMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a Website
 
UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1
 
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCostKubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
 
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAAnypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
 
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDEADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
 
Videogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfVideogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdf
 
Building AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptxBuilding AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptx
 
20150722 - AGV
20150722 - AGV20150722 - AGV
20150722 - AGV
 
9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team
 
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesAI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
 
UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8
 
Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™
 
UiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation DevelopersUiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation Developers
 
20230104 - machine vision
20230104 - machine vision20230104 - machine vision
20230104 - machine vision
 
Machine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfMachine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdf
 
Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.
 
201610817 - edge part1
201610817 - edge part1201610817 - edge part1
201610817 - edge part1
 
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve DecarbonizationUsing IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
 
Bird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemBird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystem
 
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
 

Making JavaScript Libraries More Approachable

  • 1. WHY NESTED TERNARY OPERATORS MAKE ME WANT TO KICK INANIMATE OBJECTS IN THE NUTS AKA: Making JavaScript Libraries More Approachable http://tinyurl.com/ternaryops Pamela Fox @pamelafox
  • 2. IN THE WORLD OF JS LIBRARIES...   AUTHORS USERS
  • 3. I'VE BEEN USING A LOT OF LIBRARIES THIS PAST YEAR... bootstrap.datepicker.js jquery-1.7.min.js jsrender.js bootstrap.js jquery.autosuggest.js lscache.js colorslider.js jquery.calendrical.js modernizr-1.7.js confetti.js jquery.dateinput.js personalize.js date.format.js jquery.fancybox.js phonegap.js dateinput.js jquery.mobile.js stacktrace.js dd_belatedpng.js jquery.overlay.js throttle.js facebook.js jquery.sparkline.js timeago.js facebook_js_sdk.js jquery.tablesorter.js useragent.js handlebars.js jquery.tagfield.js zepto.js highcharts.js jquery.tooltip.js
  • 4. AND SOMETIMES I SEE STUFF LIKE...   (aposed ? (aposed = !apos, (aposed ? all : '"')) : quoted ? (quoted = !quot, (quoted ? all : '"')) : ( (lftPrn ? (parenDepth++, lftPrn) : "") + (space ? (parenDepth ? "" : named ? (named = FALSE, "b") : "," ) : eq ? (parenDepth && syntaxError(), named = TRUE, 'b' + path + ':') : path ? (path.replace( rPath, parsePath ) + (prn ? (fnCall[ ++parenDepth ] = TRUE, prn) : operator) ) : operator ? all : rtPrn ? ((fnCall[ parenDepth-- ] = FALSE, rtPrn) + (prn ? (fnCall[ ++parenDepth ] = TRUE, prn) : "") ) : comma ? (fnCall[ parenDepth ] || syntaxError(), ",") : lftPrn0 ? "" : (aposed = apos, quoted = quot, '"') ))
  • 5. AND IT MAKES ME THINK OF....  
  • 6. ...WOULDN'T THIS BE BETTER?  
  • 7. THE STAGES OF BEING A USER:     1. Learn how a library works & start using it.   2. Debug a library when something goes wrong.   3. Integrate a library with their workflow.   4. BONUS: Submit a patch to the library.
  • 8. STEP 1: THIS LOOKS LIKE A USEFUL LIBRARY, LET'S SEE HOW TO USE IT. Document everything.   JSDoc, JSDuck, JoDoc, Dox, NDoc, Docco, Docco-Husky, AutoObjectDocumentation   Make the documentation easy to patch.  
  • 9. NOT ENOUGH DOCUMENTATION.   this.options.knownHelpers = { 'each': true, 'if': true, 'unless': true, 'with': true, 'log': true }; handlebars.js
  • 10. TOO MUCH DOCUMENTATION.   vs. http://handlebarsjs.com/ https://github.com/wycats/handlebars.js/
  • 12. STEP 2: UH OH, SOMETHING WENT WRONG. TIME TO DEBUG THE LIB. Make your code readable. ○ "Common conventions" ■ Idiomatic.js ■ Crockford ■ Google ■ Stoyan Stefanov ○ Descriptive variable names Make your code debuggable. ○ On *all* platforms.
  • 13. SHORTENED VARIABLE NAMES.  ar a = s.split("."), v r = "", l = a.length; for (var i = 0; i < l; i++) { var item = a[i]; if (item.length == 2) { r += "0" + item; } else { r += item; } } function login(a, b) { b = b || { perms: '' }; PhoneGap.exec(function(e) { FB.Auth.setSession(e.session, 'connected'); if (a) a(e); }, null, 'com.phonegap.facebook.Connect', 'login', b. perms.split(',') ); }
  • 14. SHORTENED VARIABLE NAMES.   FOR: The shortened names make sense.   AGAINST: Maybe to you. But not to people new to the code.   "Common sense" is not common.
  • 15. SHORTENED VARIABLE NAMES.   FOR: It makes for less bytes of code.   AGAINST: Code will get compiled to least number of bytes anyway.  
  • 16. SHORTENED VARIABLE NAMES.   FOR: It makes for shorter lines of code.   AGAINST: Readability trumps line length.  
  • 18. MISSING SEMI-COLONS.   AGAINST: It's harder to read the code.    "Readability is the single most important quality of a piece of code. Semicolons aid readability by eliminating ambiguity and ensuring that nobody ever has to spend even a second figuring out whether your code will do what it looks like it will do." Jason Kester "Relying on implicit insertion can cause subtle, hard to debug problems. Don't do it. You're better than that." Google Style Guide
  • 19. MISSING SEMI-COLONS.   AGAINST: It's harder to make non-breaking changes to the code. this: a = b + c (d + e).print() is interpreted as: a = b + c(d + e).print(); so you have to: ;(d + e).print()
  • 20. MISSING SEMI-COLONS.   FOR: It's what the core team prefers.   AGAINST: The core team aren't the only developers looking at the code. (But they might be if that's the philosophy.) Don't use your library code to show off how well you know the idiosyncrasies of a language.
  • 21. MISSING SEMI-COLONS.   AGAINST: Hacker News agrees.
  • 22. NESTED TERNARY OPERATORS.   $.qsa = $$ = function(element, selector){ var found return (element === document && idSelectorRE.test(selector)) ? ( (found = element.getElementById(RegExp.$1)) ? [found] : emptyArray ) : (element.nodeType !== 1 && element.nodeType !== 9) ? emptyArray : slice.call( classSelectorRE.test(selector) ? element.getElementsByClassName (RegExp.$1) : tagSelectorRE.test(selector) ? element.getElementsByTagName (selector) : element.querySelectorAll(selector) ) } zepto.js
  • 23. NESTED TERNARY OPERATORS.  AGAINST: They're hard to understand.  $.qsa = $$ = function(element, selector){ var found; if (element === document && idSelectorRE.test(selector)) { found = element.getElementById(RegExp.$1); return found && [found] || []; } else if (classSelectorRE.test(selector)) { return slice.call(element.getElementsByClassName(RegExp.$1)); } else if (tagSelectorRE.test(selector)) { return slice.call(element.getElementsByTagName(selector)); } else { return slice.call(attemptQuerySelectorAll(element, selector)); } } If you have the choice between two styles and one is more readable, choose that one.
  • 24. NESTED TERNARY OPERATORS.   AGAINST: It's hard to debug the nested statements.   FOR: You can debug them with breakpoints.   AGAINST: You can't always use fancy debuggers. See: Android, IE
  • 25. NESTED TERNARY OPERATORS.   FOR: They perform better than if/else.   AGAINST: Compilers convert if/else to ternary. Try in UglifyJS or Closure Compiler.
  • 26. STEP 3: OK, ALL WORKING. TIME TO INTEGRATE WITH MY WORKFLOW. Try your code with popular JS build tools ● JSHint ● Closure Compiler / UglifyJS ● Grunt   If it requires options, specify them or inline them into the code.
  • 27. UNSPECIFIED JSHINT OPTIONS.   [jshint] Error(s) in ./application/static/js/libs/bootstrap.js: Missing semicolon. (line: 24, character: 5) > "use strict" Comma warnings can be turned off with 'laxcomma' (line: 31, character: 9) > , thisStyle = thisBody.style Bad line breaking before ','. (line: 30, character: 48) > var thisBody = document.body || document.documentElement ... Too many errors. (8% scanned). (line: 139, character: 73) /*jshint asi:true, laxbreak:true, laxcomma:true, expr:true, boss:true */
  • 28. STEP 4: WHEE, IT WORKS, NOW I JUST WANNA SUBMIT THIS ONE CHANGE. Make it easy to build.   Make the tests easy to run.   ...use familiar tools and languages.
  • 30. SO, IF YOU'RE A LIBRARY... WHICH ONE DO YOU WANT TO BE? elite approachable vs. AUTHORS USERS USERS AUTHORS