SlideShare ist ein Scribd-Unternehmen logo
1 von 48
Downloaden Sie, um offline zu lesen
Turn	
  your	
  spaghe.	
  code	
  into	
  
ravioli	
  with	
  JavaScript	
  modules	
  
Jeremiah	
  Orr	
  
@JerryOnJava 	
  jerryorr.com	
  
	
  
Spider	
  Strategies,	
  Inc	
  
thedash.com	
  
What	
  is	
  spaghe.	
  code?	
  
Source:	
  hBps://www.flickr.com/photos/avlxyz/4800088303/	
  
registraLon.js	
  
$('input[name=presenting]').change(function () {!
var presenting = $('input[name=presenting]:checked')!
.val() == 'yes'!
!
$('.payment').toggleClass('hidden', presenting)!
!
if (presenting) {!
$('.payment .has-error').removeClass('has-error')!
$('.payment .help-block').remove()!
$('.payment input').data('valid', true)!
}!
})!
registraLon.js	
  
$('input#name').on('change input blur', function () {!
var input = $(this)!
var inputGroup = input.parent()!
!
inputGroup.find('.help-block').remove()!
!
var name = input.val()!
var valid = !empty(name)!
!
inputGroup.toggleClass('has-error', !valid)!
if (!valid) {!
input.after(!
'<span class="help-block">Name is required</span>')!
}!
!
input.data('valid', valid)!
})!
registraLon.js	
  
$('input#email').on('change input blur', function () {!
var input = $(this)!
var inputGroup = input.parent()!
!
inputGroup.find('.help-block').remove()!
!
var val = input.val()!
var valid = !empty(val) && /.+@.+..+/.test(val)!
!
inputGroup.toggleClass('has-error', !valid)!
if (!valid) {!
input.after('<span class="help-block">'!
+ 'A valid email address is required</span>')!
}!
!
input.data('valid', valid)!
})!
!
What	
  is	
  spaghe.	
  code?	
  
DRY	
  WET	
   Loosely	
  Tightly	
  Coupled	
  
SeparaLon	
  of	
  Concerns	
  Doing	
  Too	
  Many	
  Things	
  At	
  Once	
  
Easy	
  to	
  Understand	
  Big	
  Ball	
  of	
  Code	
  
Safe	
  to	
  Modify	
  Afraid	
  to	
  Touch	
  
Well-­‐tested	
  Tests?	
  Hah!	
  
What	
  is	
  spaghe.	
  code?	
  
Source:	
  hBps://www.flickr.com/photos/avlxyz/4800088303/	
  
What	
  about	
  ravioli?	
  
Source:	
  hBp://cocinandoespero.blogspot.com/2009/11/ravioli-­‐rellenos-­‐de-­‐setas-­‐del-­‐bosque.html	
  
empty.js	
  
module.exports = function (v) {!
if (!v) {!
return true!
}!
!
if (typeof v === 'string' && v.trim() == '') {!
return true!
}!
!
return false!
}!
required.js	
  
var empty = require('./empty')!
!
module.exports = function (val, label) {!
label = label || 'Field’!
!
return empty(val) ? (label + ' is required') : null!
}!
email.js	
  
module.exports = function (val, label) {!
label = label || 'Field’!
!
return /.+@.+..+/.test(val) ? null !
: (label + ' must be a valid email address')!
}!
validate.js	
  
module.exports = function (validation, label) {!
return function (value) {!
return validation(value, label)!
}!
}!
validate-­‐input.js	
  
var $ = require('jquery')!
var _ = require('lodash')!
!
module.exports = function (input, validations) {!
return function () {!
var val = $(input).val()!
!
var error = _.chain(validations)!
.map(function (validation) {!
return validation(val)!
})!
.compact()!
.first().value()!
!
return error!
}!
}!
Composed	
  ValidaLon	
  FuncLon	
  
var $ = require('jquery')!
var required = require('./validation/required')!
var email = require('./validation/email')!
var validate = require('./validation/validate')!
var validateInput = require('./validation/validate-input')!
!
var validateEmail = validateInput(!
$('input#email'), !
[!
validate(required, 'Email'), !
validate(email, 'Email')!
])!
!
// This will now get the input value, run through!
// all the validations, and return an error message!
// if validation fails!
validateEmail()!
Even	
  more	
  composiLon!	
  
module.exports = function (formGroup, validator) {!
var input = formGroup.find('input')!
input.on('change input blur', function () {!
!
formGroup.find('.help-block').remove()!
!
var error = validator()!
formGroup.toggleClass('has-error', !!error)!
if (error) {!
input.after('<span class="help-block">' !
+ error + '</span>')!
}!
})!
}!
watch-­‐and-­‐validate.js	
  
Even	
  more	
  composiLon!	
  
var validateEmail = validateInput(!
$('input#email'), !
[!
validate(required, 'Email'), !
validate(email, 'Email')!
])!
!
watchAndValidate($('.form-group.email'), validateEmail)!
!
!
var validateName = validateInput(!
$('input#name'), !
[ validate(required, 'Name') ])!
!
watchAndValidate($('.form-group.name'), validateName)!
What	
  is	
  ravioli	
  (modular)	
  code?	
  
DRY	
  
Loosely	
  Coupled	
  
SeparaLon	
  of	
  Concerns	
  
Easy	
  to	
  Understand	
  
Safe	
  to	
  Modify	
  
Well-­‐tested	
  
The	
  UNIX	
  Philosophy	
  
Do	
  one	
  thing	
  and	
  do	
  it	
  well	
  
	
  	
  -­‐	
  Doug	
  McIlroy	
  (1978)	
  
	
  
Many	
  UNIX	
  programs	
  do	
  quite	
  trivial	
  things	
  in	
  
isolaCon,	
  but,	
  combined	
  with	
  other	
  programs,	
  
become	
  general	
  and	
  useful	
  tools.	
  
	
  	
  -­‐	
  Brian	
  W.	
  Kernighan	
  and	
  Rob	
  Pike	
  (1984)	
  
	
  
Small	
  is	
  beauCful.	
  	
  
	
  	
  -­‐	
  Mike	
  Gancarz	
  (1994)	
  
	
  
Simple	
  UNIX	
  Tools	
  
•  find	
  -­‐	
  searches	
  a	
  directory	
  structure	
  for	
  files	
  
matching	
  an	
  expression	
  
•  xargs	
  -­‐	
  executes	
  an	
  arbitrary	
  command	
  using	
  
the	
  output	
  of	
  a	
  previous	
  command	
  as	
  arguments	
  
•  egrep	
  -­‐	
  searches	
  for	
  text	
  matching	
  a	
  given	
  
regular	
  expression	
  
•  identify	
  -­‐	
  retrieves	
  image	
  metadata	
  (part	
  of	
  
ImageMagick)	
  
•  cut	
  -­‐	
  extracts	
  segments	
  of	
  text	
  
•  tar	
  -­‐	
  creates	
  file	
  archives	
  
A	
  Complex	
  Task	
  
I	
  want	
  to	
  search	
  through	
  my	
  file	
  system	
  for	
  all	
  
photos	
  taken	
  during	
  the	
  winter	
  holiday	
  season	
  of	
  
every	
  year,	
  and	
  put	
  them	
  in	
  a	
  single	
  archive.	
  
Solved	
  by	
  composing	
  simple	
  programs	
  
find . -iname '*.jp*g' -print0 !
| xargs -0 -L 1 -I @ !
identify -format '%[EXIF:DateTime] %d/%fn' @ !
| egrep '^[[:digit:]]{4}:12' !
| cut -d' ' -f3- !
| tar -cf december.tar -T -!
 While	
  designing	
  the	
  future,	
  it’s	
  
important	
  not	
  to	
  forget	
  the	
  
lessons	
  of	
  the	
  past	
  
There	
  is	
  such	
  a	
  thing	
  as	
  a	
  Beethoven	
  or	
  Mozart	
  of	
  soUware	
  design.	
  
	
  -­‐	
  ScoV	
  Locklin	
  
VanillaJS	
  modules	
  
(function (global) { !
var chicken = global.chicken = {}!
!
chicken.thesis = function () {!
// I sure hope the browser finished loading egg.js !
// and sprintf.js by now...!
return sprintf('You need the %s before the %s.', !
chicken.sound(), egg.sound())!
}!
!
chicken.sound = function () {!
return 'cluck'!
}!
!
}(window))!
chicken.js!
VanillaJS	
  modules	
  
(function (global) { !
var egg = global.egg = {}!
!
egg.thesis = function () {!
// I sure hope the browser finished loading!
// chicken.js and sprintf.js by now...!
return sprintf('You need the %s before the %s.',!
egg.sound(), chicken.sound())!
}!
!
egg.sound = function () {!
return 'crack'!
}!
!
}(window))!
egg.js!
VanillaJS	
  modules	
  
// I sure hope the browser finished loading jquery !
// by now...!
$(document).ready(function () {!
// I sure hope the browser finished loading egg.js !
// and chicken.js by now...!
!
$('<div/>').html(chicken.thesis())!
.appendTo(document.body)!
!
$('<div/>').html(egg.thesis())!
.appendTo(document.body)!
})!
debate.js!
VanillaJS	
  modules	
  
<script src="jquery-2.1.4.min.js”></script>!
<script src="sprintf.min.js"></script>!
<script src="chicken.js"></script>!
<script src="egg.js"></script>!
<script src="debate.js"></script>	
  
index.html!
Browserify	
  modules	
  
var egg = require('./egg')!
var sprintf = require('sprintf')!
!
module.exports.thesis = function () {!
return sprintf('You need the %s before the %s.', !
sound(), egg.sound())!
}!
!
var sound = module.exports.sound = function () {!
return 'cluck'!
}!
chicken.js!
Browserify	
  and	
  npm	
  
•  Over	
  150,000	
  packages	
  on	
  npmjs.com	
  
•  Can	
  point	
  npm	
  to	
  arbitrary	
  URLs	
  
•  Easy	
  to	
  install	
  packages	
  
•  Easy	
  to	
  upgrade	
  packages	
  
Is	
  it	
  really	
  that	
  easy?	
  
In	
  just	
  a	
  few	
  minutes,	
  we…	
  
•  Imported	
  three	
  3rd	
  party	
  libraries	
   Easy	
  to	
  upgrade!	
  
•  Created	
  several	
  Lght,	
  focused	
  
modules	
  
Easy	
  to	
  test!	
  
•  Integrated	
  a	
  templaLng	
  system	
   Safe	
  from	
  XSS!	
  
•  Set	
  up	
  a	
  quick	
  turnaround	
  
development	
  process	
  
Sourcemaps,	
  too!	
  
•  Set	
  up	
  producLon	
  build	
  process,	
  
producing	
  one	
  bundle	
  with	
  all	
  
JavaScript	
  and	
  templates	
  
	
  
Minified,	
  too!	
  
RequireJS	
  
	
  
•  Helps	
  you	
  write	
  Lght,	
  focused	
  modules	
  
•  Manages	
  complex	
  dependency	
  trees	
  
•  Only	
  includes	
  modules	
  you	
  actually	
  use	
  
	
  
•  Can	
  produce	
  a	
  single	
  bundle	
  
Like	
  Browserify…	
  
	
  
RequireJS	
  
Unlike	
  Browserify	
  (in	
  a	
  good	
  way)	
  
	
  
Build	
  not	
  required	
  when	
  developing!	
  
RequireJS	
  modules	
  
define(function (require) {!
var egg = require('./egg')!
var sprintf = require('./sprintf')!
!
var module = {}!
module.thesis = function () {!
return sprintf('You need the %s before the %s.', !
sound(), egg.sound())!
}!
!
var sound = module.sound = function () {!
return 'cluck'!
}!
!
return module!
})!
chicken.js!
RequireJS	
  modules	
  
<html>!
<body>!
</body>!
!
<script data-main="scripts/debate" !
src="scripts/require.js"></script>!
!
</html>!
index.html!
RequireJS	
  
Unlike	
  Browserify	
  (in	
  a	
  bad	
  way)	
  
	
  
•  Cumbersome	
  syntax	
  (IMO)	
  
•  No	
  package	
  manager;	
  need	
  to	
  manually	
  install,	
  
upgrade,	
  and	
  manage	
  3rd	
  party	
  library	
  
dependences	
  
•  More	
  configuraLon	
  
ES6	
  Modules	
  
•  ECMAScript	
  version	
  6	
  (the	
  next	
  JavaScript	
  
standard)	
  
•  NaLve	
  browser	
  support	
  (someday)	
  
•  Only	
  loads	
  the	
  modules	
  you	
  need	
  
•  Simple	
  syntax	
  
ES6	
  Modules	
  
chicken.js!
import * as egg from './egg'!
import sprintf from 'sprintf'!
!
export function thesis () {!
return sprintf('You need the %s before the %s.', !
sound(), egg.sound())!
}!
!
export function sound () {!
return 'cluck'!
}!
ES6	
  Modules	
  
•  Need	
  something	
  to	
  create	
  a	
  producLon	
  bundle	
  
•  Need	
  a	
  transpiler	
  unLl	
  supported	
  in	
  target	
  
browsers	
  (babel,	
  Browserify	
  +	
  babelify)	
  
So	
  which	
  module	
  system	
  should	
  I	
  use?	
  
The	
  nice	
  thing	
  about	
  standards	
  is	
  that	
  you	
  have	
  
so	
  many	
  to	
  choose	
  from.	
  	
  
-­‐	
  Andrew	
  S.	
  Tanenbaum	
  
	
  
hBps://xkcd.com/927/	
  
Simplicity	
  is	
  prerequisite	
  for	
  reliability.	
  
	
  -­‐	
  Edsger	
  W.	
  Dijkstra	
  
Simplicity	
  is	
  the	
  ulCmate	
  sophisCcaCon.	
  	
  
-­‐	
  Leonardo	
  da	
  Vinci	
  
Any	
  intelligent	
  fool	
  can	
  make	
  things	
  bigger,	
  more	
  complex,	
  
and	
  more	
  violent.	
  It	
  takes	
  a	
  touch	
  of	
  genius	
  -­‐	
  and	
  a	
  lot	
  of	
  
courage	
  -­‐	
  to	
  move	
  in	
  	
  the	
  opposite	
  direcCon.	
  	
  
–	
  Albert	
  Einstein	
  
“Simplicity	
  is	
  about	
  subtracCng	
  the	
  obvious	
  and	
  adding	
  the	
  
meaningful.”	
  
-­‐	
  John	
  Maeda	
  
Don’t	
  write	
  complex	
  so7ware…	
  
Write	
  many	
  pieces	
  of	
  simple,	
  thoroughly	
  
tested	
  sopware…	
  
And	
  compose	
  these	
  simple	
  pieces	
  of	
  
sopware	
  to	
  do	
  complex	
  things.	
  
Jeremiah	
  Orr	
  
@JerryOnJava 	
  jerryorr.com	
  
Spider	
  Strategies,	
  Inc	
  
thedash.com	
  
Thanks	
  for	
  listening!	
  
All	
  code	
  examples	
  available	
  at	
  
	
  hBps://github.com/jerryorr/psuweb-­‐modularity	
  

Weitere ähnliche Inhalte

Was ist angesagt?

The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5a
rajivmordani
 
Mojolicious, real-time web framework
Mojolicious, real-time web frameworkMojolicious, real-time web framework
Mojolicious, real-time web framework
taggg
 
jQuery Anti-Patterns for Performance & Compression
jQuery Anti-Patterns for Performance & CompressionjQuery Anti-Patterns for Performance & Compression
jQuery Anti-Patterns for Performance & Compression
Paul Irish
 
Avinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPressAvinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPress
wpnepal
 

Was ist angesagt? (20)

The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5a
 
jQuery in 15 minutes
jQuery in 15 minutesjQuery in 15 minutes
jQuery in 15 minutes
 
Mojolicious - Perl Framework for the Real-Time Web (Lightning Talk)
Mojolicious - Perl Framework for the Real-Time Web (Lightning Talk)Mojolicious - Perl Framework for the Real-Time Web (Lightning Talk)
Mojolicious - Perl Framework for the Real-Time Web (Lightning Talk)
 
And the Greatest of These Is ... Rack Support
And the Greatest of These Is ... Rack SupportAnd the Greatest of These Is ... Rack Support
And the Greatest of These Is ... Rack Support
 
jQuery Performance Tips and Tricks (2011)
jQuery Performance Tips and Tricks (2011)jQuery Performance Tips and Tricks (2011)
jQuery Performance Tips and Tricks (2011)
 
Mojolicious, real-time web framework
Mojolicious, real-time web frameworkMojolicious, real-time web framework
Mojolicious, real-time web framework
 
Assetic (Symfony Live Paris)
Assetic (Symfony Live Paris)Assetic (Symfony Live Paris)
Assetic (Symfony Live Paris)
 
jQuery Anti-Patterns for Performance & Compression
jQuery Anti-Patterns for Performance & CompressionjQuery Anti-Patterns for Performance & Compression
jQuery Anti-Patterns for Performance & Compression
 
Short lived immutable servers with masterless puppet
Short lived immutable servers with masterless puppetShort lived immutable servers with masterless puppet
Short lived immutable servers with masterless puppet
 
A piece of sugar in your client-side development
A piece of sugar in your client-side developmentA piece of sugar in your client-side development
A piece of sugar in your client-side development
 
Rails for Beginners - Le Wagon
Rails for Beginners - Le WagonRails for Beginners - Le Wagon
Rails for Beginners - Le Wagon
 
Frontin like-a-backer
Frontin like-a-backerFrontin like-a-backer
Frontin like-a-backer
 
Avinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPressAvinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPress
 
Symfony Messenger (Symfony Live San Francisco)
Symfony Messenger (Symfony Live San Francisco)Symfony Messenger (Symfony Live San Francisco)
Symfony Messenger (Symfony Live San Francisco)
 
How I started to love design patterns
How I started to love design patternsHow I started to love design patterns
How I started to love design patterns
 
Mojolicious. Веб в коробке!
Mojolicious. Веб в коробке!Mojolicious. Веб в коробке!
Mojolicious. Веб в коробке!
 
Mojolicious - A new hope
Mojolicious - A new hopeMojolicious - A new hope
Mojolicious - A new hope
 
With a Mighty Hammer
With a Mighty HammerWith a Mighty Hammer
With a Mighty Hammer
 
Boost your angular app with web workers
Boost your angular app with web workersBoost your angular app with web workers
Boost your angular app with web workers
 
Fórum de Software Livre do Serpro RJ 2009
Fórum de Software Livre do Serpro RJ 2009Fórum de Software Livre do Serpro RJ 2009
Fórum de Software Livre do Serpro RJ 2009
 

Ähnlich wie Turn your spaghetti code into ravioli with JavaScript modules

Javascript MVC & Backbone Tips & Tricks
Javascript MVC & Backbone Tips & TricksJavascript MVC & Backbone Tips & Tricks
Javascript MVC & Backbone Tips & Tricks
Hjörtur Hilmarsson
 
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasmineSingle Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Paulo Ragonha
 
Jarv.us Showcase — SenchaCon 2011
Jarv.us Showcase — SenchaCon 2011Jarv.us Showcase — SenchaCon 2011
Jarv.us Showcase — SenchaCon 2011
Chris Alfano
 
Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012
Michelangelo van Dam
 

Ähnlich wie Turn your spaghetti code into ravioli with JavaScript modules (20)

Javascript MVC & Backbone Tips & Tricks
Javascript MVC & Backbone Tips & TricksJavascript MVC & Backbone Tips & Tricks
Javascript MVC & Backbone Tips & Tricks
 
Es.next
Es.nextEs.next
Es.next
 
FrontInBahia 2014: 10 dicas de desempenho para apps mobile híbridas
FrontInBahia 2014: 10 dicas de desempenho para apps mobile híbridasFrontInBahia 2014: 10 dicas de desempenho para apps mobile híbridas
FrontInBahia 2014: 10 dicas de desempenho para apps mobile híbridas
 
A re introduction to webpack - reactfoo - mumbai
A re introduction to webpack - reactfoo - mumbaiA re introduction to webpack - reactfoo - mumbai
A re introduction to webpack - reactfoo - mumbai
 
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasmineSingle Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
 
Jarv.us Showcase — SenchaCon 2011
Jarv.us Showcase — SenchaCon 2011Jarv.us Showcase — SenchaCon 2011
Jarv.us Showcase — SenchaCon 2011
 
Lecture 03 - JQuery.pdf
Lecture 03 - JQuery.pdfLecture 03 - JQuery.pdf
Lecture 03 - JQuery.pdf
 
Ember testing internals with ember cli
Ember testing internals with ember cliEmber testing internals with ember cli
Ember testing internals with ember cli
 
Bonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsBonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node js
 
Moving to modules
Moving to modulesMoving to modules
Moving to modules
 
JavaScript Promise
JavaScript PromiseJavaScript Promise
JavaScript Promise
 
Building a real life application in node js
Building a real life application in node jsBuilding a real life application in node js
Building a real life application in node js
 
Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012
 
Get into the FLOW with Extbase
Get into the FLOW with ExtbaseGet into the FLOW with Extbase
Get into the FLOW with Extbase
 
Javascript first-class citizenery
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenery
 
Rails is not just Ruby
Rails is not just RubyRails is not just Ruby
Rails is not just Ruby
 
2013-06-15 - Software Craftsmanship mit JavaScript
2013-06-15 - Software Craftsmanship mit JavaScript2013-06-15 - Software Craftsmanship mit JavaScript
2013-06-15 - Software Craftsmanship mit JavaScript
 
2013-06-24 - Software Craftsmanship with JavaScript
2013-06-24 - Software Craftsmanship with JavaScript2013-06-24 - Software Craftsmanship with JavaScript
2013-06-24 - Software Craftsmanship with JavaScript
 
Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12
 
Node.js
Node.jsNode.js
Node.js
 

Kürzlich hochgeladen

Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
masabamasaba
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
masabamasaba
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
masabamasaba
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
masabamasaba
 

Kürzlich hochgeladen (20)

Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptx
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
What Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationWhat Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the Situation
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
 

Turn your spaghetti code into ravioli with JavaScript modules

  • 1. Turn  your  spaghe.  code  into   ravioli  with  JavaScript  modules   Jeremiah  Orr   @JerryOnJava  jerryorr.com     Spider  Strategies,  Inc   thedash.com  
  • 2. What  is  spaghe.  code?   Source:  hBps://www.flickr.com/photos/avlxyz/4800088303/  
  • 3.
  • 4. registraLon.js   $('input[name=presenting]').change(function () {! var presenting = $('input[name=presenting]:checked')! .val() == 'yes'! ! $('.payment').toggleClass('hidden', presenting)! ! if (presenting) {! $('.payment .has-error').removeClass('has-error')! $('.payment .help-block').remove()! $('.payment input').data('valid', true)! }! })!
  • 5. registraLon.js   $('input#name').on('change input blur', function () {! var input = $(this)! var inputGroup = input.parent()! ! inputGroup.find('.help-block').remove()! ! var name = input.val()! var valid = !empty(name)! ! inputGroup.toggleClass('has-error', !valid)! if (!valid) {! input.after(! '<span class="help-block">Name is required</span>')! }! ! input.data('valid', valid)! })!
  • 6. registraLon.js   $('input#email').on('change input blur', function () {! var input = $(this)! var inputGroup = input.parent()! ! inputGroup.find('.help-block').remove()! ! var val = input.val()! var valid = !empty(val) && /.+@.+..+/.test(val)! ! inputGroup.toggleClass('has-error', !valid)! if (!valid) {! input.after('<span class="help-block">'! + 'A valid email address is required</span>')! }! ! input.data('valid', valid)! })! !
  • 7. What  is  spaghe.  code?   DRY  WET   Loosely  Tightly  Coupled   SeparaLon  of  Concerns  Doing  Too  Many  Things  At  Once   Easy  to  Understand  Big  Ball  of  Code   Safe  to  Modify  Afraid  to  Touch   Well-­‐tested  Tests?  Hah!  
  • 8. What  is  spaghe.  code?   Source:  hBps://www.flickr.com/photos/avlxyz/4800088303/  
  • 9. What  about  ravioli?   Source:  hBp://cocinandoespero.blogspot.com/2009/11/ravioli-­‐rellenos-­‐de-­‐setas-­‐del-­‐bosque.html  
  • 10. empty.js   module.exports = function (v) {! if (!v) {! return true! }! ! if (typeof v === 'string' && v.trim() == '') {! return true! }! ! return false! }!
  • 11. required.js   var empty = require('./empty')! ! module.exports = function (val, label) {! label = label || 'Field’! ! return empty(val) ? (label + ' is required') : null! }!
  • 12. email.js   module.exports = function (val, label) {! label = label || 'Field’! ! return /.+@.+..+/.test(val) ? null ! : (label + ' must be a valid email address')! }!
  • 13. validate.js   module.exports = function (validation, label) {! return function (value) {! return validation(value, label)! }! }!
  • 14. validate-­‐input.js   var $ = require('jquery')! var _ = require('lodash')! ! module.exports = function (input, validations) {! return function () {! var val = $(input).val()! ! var error = _.chain(validations)! .map(function (validation) {! return validation(val)! })! .compact()! .first().value()! ! return error! }! }!
  • 15. Composed  ValidaLon  FuncLon   var $ = require('jquery')! var required = require('./validation/required')! var email = require('./validation/email')! var validate = require('./validation/validate')! var validateInput = require('./validation/validate-input')! ! var validateEmail = validateInput(! $('input#email'), ! [! validate(required, 'Email'), ! validate(email, 'Email')! ])! ! // This will now get the input value, run through! // all the validations, and return an error message! // if validation fails! validateEmail()!
  • 16. Even  more  composiLon!   module.exports = function (formGroup, validator) {! var input = formGroup.find('input')! input.on('change input blur', function () {! ! formGroup.find('.help-block').remove()! ! var error = validator()! formGroup.toggleClass('has-error', !!error)! if (error) {! input.after('<span class="help-block">' ! + error + '</span>')! }! })! }! watch-­‐and-­‐validate.js  
  • 17. Even  more  composiLon!   var validateEmail = validateInput(! $('input#email'), ! [! validate(required, 'Email'), ! validate(email, 'Email')! ])! ! watchAndValidate($('.form-group.email'), validateEmail)! ! ! var validateName = validateInput(! $('input#name'), ! [ validate(required, 'Name') ])! ! watchAndValidate($('.form-group.name'), validateName)!
  • 18. What  is  ravioli  (modular)  code?   DRY   Loosely  Coupled   SeparaLon  of  Concerns   Easy  to  Understand   Safe  to  Modify   Well-­‐tested  
  • 19. The  UNIX  Philosophy   Do  one  thing  and  do  it  well      -­‐  Doug  McIlroy  (1978)     Many  UNIX  programs  do  quite  trivial  things  in   isolaCon,  but,  combined  with  other  programs,   become  general  and  useful  tools.      -­‐  Brian  W.  Kernighan  and  Rob  Pike  (1984)     Small  is  beauCful.        -­‐  Mike  Gancarz  (1994)    
  • 20. Simple  UNIX  Tools   •  find  -­‐  searches  a  directory  structure  for  files   matching  an  expression   •  xargs  -­‐  executes  an  arbitrary  command  using   the  output  of  a  previous  command  as  arguments   •  egrep  -­‐  searches  for  text  matching  a  given   regular  expression   •  identify  -­‐  retrieves  image  metadata  (part  of   ImageMagick)   •  cut  -­‐  extracts  segments  of  text   •  tar  -­‐  creates  file  archives  
  • 21. A  Complex  Task   I  want  to  search  through  my  file  system  for  all   photos  taken  during  the  winter  holiday  season  of   every  year,  and  put  them  in  a  single  archive.  
  • 22. Solved  by  composing  simple  programs   find . -iname '*.jp*g' -print0 ! | xargs -0 -L 1 -I @ ! identify -format '%[EXIF:DateTime] %d/%fn' @ ! | egrep '^[[:digit:]]{4}:12' ! | cut -d' ' -f3- ! | tar -cf december.tar -T -!
  • 23.  While  designing  the  future,  it’s   important  not  to  forget  the   lessons  of  the  past   There  is  such  a  thing  as  a  Beethoven  or  Mozart  of  soUware  design.    -­‐  ScoV  Locklin  
  • 24. VanillaJS  modules   (function (global) { ! var chicken = global.chicken = {}! ! chicken.thesis = function () {! // I sure hope the browser finished loading egg.js ! // and sprintf.js by now...! return sprintf('You need the %s before the %s.', ! chicken.sound(), egg.sound())! }! ! chicken.sound = function () {! return 'cluck'! }! ! }(window))! chicken.js!
  • 25. VanillaJS  modules   (function (global) { ! var egg = global.egg = {}! ! egg.thesis = function () {! // I sure hope the browser finished loading! // chicken.js and sprintf.js by now...! return sprintf('You need the %s before the %s.',! egg.sound(), chicken.sound())! }! ! egg.sound = function () {! return 'crack'! }! ! }(window))! egg.js!
  • 26. VanillaJS  modules   // I sure hope the browser finished loading jquery ! // by now...! $(document).ready(function () {! // I sure hope the browser finished loading egg.js ! // and chicken.js by now...! ! $('<div/>').html(chicken.thesis())! .appendTo(document.body)! ! $('<div/>').html(egg.thesis())! .appendTo(document.body)! })! debate.js!
  • 27. VanillaJS  modules   <script src="jquery-2.1.4.min.js”></script>! <script src="sprintf.min.js"></script>! <script src="chicken.js"></script>! <script src="egg.js"></script>! <script src="debate.js"></script>   index.html!
  • 28.
  • 29. Browserify  modules   var egg = require('./egg')! var sprintf = require('sprintf')! ! module.exports.thesis = function () {! return sprintf('You need the %s before the %s.', ! sound(), egg.sound())! }! ! var sound = module.exports.sound = function () {! return 'cluck'! }! chicken.js!
  • 30. Browserify  and  npm   •  Over  150,000  packages  on  npmjs.com   •  Can  point  npm  to  arbitrary  URLs   •  Easy  to  install  packages   •  Easy  to  upgrade  packages  
  • 31. Is  it  really  that  easy?  
  • 32. In  just  a  few  minutes,  we…   •  Imported  three  3rd  party  libraries   Easy  to  upgrade!   •  Created  several  Lght,  focused   modules   Easy  to  test!   •  Integrated  a  templaLng  system   Safe  from  XSS!   •  Set  up  a  quick  turnaround   development  process   Sourcemaps,  too!   •  Set  up  producLon  build  process,   producing  one  bundle  with  all   JavaScript  and  templates     Minified,  too!  
  • 33.
  • 34.
  • 35. RequireJS     •  Helps  you  write  Lght,  focused  modules   •  Manages  complex  dependency  trees   •  Only  includes  modules  you  actually  use     •  Can  produce  a  single  bundle   Like  Browserify…    
  • 36. RequireJS   Unlike  Browserify  (in  a  good  way)     Build  not  required  when  developing!  
  • 37. RequireJS  modules   define(function (require) {! var egg = require('./egg')! var sprintf = require('./sprintf')! ! var module = {}! module.thesis = function () {! return sprintf('You need the %s before the %s.', ! sound(), egg.sound())! }! ! var sound = module.sound = function () {! return 'cluck'! }! ! return module! })! chicken.js!
  • 38. RequireJS  modules   <html>! <body>! </body>! ! <script data-main="scripts/debate" ! src="scripts/require.js"></script>! ! </html>! index.html!
  • 39. RequireJS   Unlike  Browserify  (in  a  bad  way)     •  Cumbersome  syntax  (IMO)   •  No  package  manager;  need  to  manually  install,   upgrade,  and  manage  3rd  party  library   dependences   •  More  configuraLon  
  • 40.
  • 41. ES6  Modules   •  ECMAScript  version  6  (the  next  JavaScript   standard)   •  NaLve  browser  support  (someday)   •  Only  loads  the  modules  you  need   •  Simple  syntax  
  • 42. ES6  Modules   chicken.js! import * as egg from './egg'! import sprintf from 'sprintf'! ! export function thesis () {! return sprintf('You need the %s before the %s.', ! sound(), egg.sound())! }! ! export function sound () {! return 'cluck'! }!
  • 43. ES6  Modules   •  Need  something  to  create  a  producLon  bundle   •  Need  a  transpiler  unLl  supported  in  target   browsers  (babel,  Browserify  +  babelify)  
  • 44. So  which  module  system  should  I  use?   The  nice  thing  about  standards  is  that  you  have   so  many  to  choose  from.     -­‐  Andrew  S.  Tanenbaum    
  • 46. Simplicity  is  prerequisite  for  reliability.    -­‐  Edsger  W.  Dijkstra   Simplicity  is  the  ulCmate  sophisCcaCon.     -­‐  Leonardo  da  Vinci   Any  intelligent  fool  can  make  things  bigger,  more  complex,   and  more  violent.  It  takes  a  touch  of  genius  -­‐  and  a  lot  of   courage  -­‐  to  move  in    the  opposite  direcCon.     –  Albert  Einstein   “Simplicity  is  about  subtracCng  the  obvious  and  adding  the   meaningful.”   -­‐  John  Maeda  
  • 47. Don’t  write  complex  so7ware…   Write  many  pieces  of  simple,  thoroughly   tested  sopware…   And  compose  these  simple  pieces  of   sopware  to  do  complex  things.  
  • 48. Jeremiah  Orr   @JerryOnJava  jerryorr.com   Spider  Strategies,  Inc   thedash.com   Thanks  for  listening!   All  code  examples  available  at    hBps://github.com/jerryorr/psuweb-­‐modularity