SlideShare a Scribd company logo
1 of 46
Download to read offline
Programming To
   Patterns
How I used to write
How I used to write

        Classes
        DatePicker
       FormValidator
             Fx
          Request
         Slideshow
            etc...
How I used to write
var myApp = {
  init: function(){
   myApp.apples()                                         Classes
   myApp.orange()                                         DatePicker
   myApp.lemons()                                        FormValidator
 },                                                            Fx
 apples: function(){                                        Request
   $$(‘div.apple’).each(function(apple) {                  Slideshow
      var form = apple.getElement(‘form’);                    etc...
      form.addEvent(‘submit’, funciton(event){ ....});
   });
 },
 orange: function(){
   $(‘orange’).getElements(‘li’).each...
 },
  etc...
How I used to write
var myApp = {
  init: function(){
   myApp.apples()                                         Classes
   myApp.orange()                                         DatePicker
   myApp.lemons()                                        FormValidator
 },                                                            Fx
 apples: function(){                                        Request
   $$(‘div.apple’).each(function(apple) {                  Slideshow
      var form = apple.getElement(‘form’);                    etc...
      form.addEvent(‘submit’, funciton(event){ ....});
   });
 },
 orange: function(){
   $(‘orange’).getElements(‘li’).each...
 },
  etc...


                       This tends to get out of hand
Banging it out...
<script>
window.addEvent(‘domready’, function(){
 $(‘myForm’).addEvent(‘submit’, function(evt){
      evt.preventDefault();
      this.send({
       onComplete: function(result){ ... },
       update: $(‘myContainer’)
      });
 });
});
</script>


       This is very tempting.
Pros
• Writing the logic for a specific app is fast
  and furious

• The test environment is the app
Pros
• Writing the logic for a specific app is fast
  and furious

• The test environment is the app
                 & Cons
• It’s much harder to maintain
• A high percentage of code you write for the
 app isn’t reusable
Using Classes
Using Classes
  This is how
MooTools does it
var Human = new Class({
    isAlive: true,
    energy: 1,
    eat: function(){
        this.energy++;
    }
});




                          Human
Using Classes
  This is how
MooTools does it
var Human = new Class({
    isAlive: true,
    energy: 1,
    eat: function(){
        this.energy++;
    }
});


var bob = new Human();
//bob.energy === 1

bob.eat();
//bob.energy === 2




                          Human




                                     bob
Extending Classes
Extending Classes
var Human = new Class({
    initialize: function(name, age){
        this.name = name;
        this.age = age;
    },
    isAlive: true,
    energy: 1,
    eat: function(){
        this.energy++;
    }
});
Extending Classes
var Human = new Class({                var Ninja = new Class({
    initialize: function(name, age){     Extends: Human,
        this.name = name;                initialize: function(side, name, age){
        this.age = age;                     this.side = side;
    },                                      this.parent(name, age);
    isAlive: true,                       },
    energy: 1,                           energy: 100,
    eat: function(){                     attack: function(target){
        this.energy++;                      this.energy = this.energy - 5;
    }                                       target.isAlive = false;
});                                      }
                                       });
Extending Classes
var Human = new Class({                var Ninja = new Class({
    initialize: function(name, age){     Extends: Human,
        this.name = name;                initialize: function(side, name, age){
        this.age = age;                     this.side = side;
    },                                      this.parent(name, age);
    isAlive: true,                       },
    energy: 1,                           energy: 100,
    eat: function(){                     attack: function(target){
        this.energy++;                      this.energy = this.energy - 5;
    }                                       target.isAlive = false;
});                                      }
                                       });
Extending Classes
var Human = new Class({                      var Ninja = new Class({
    initialize: function(name, age){           Extends: Human,
        this.name = name;                      initialize: function(side, name, age){
        this.age = age;                           this.side = side;
    },                                            this.parent(name, age);
    isAlive: true,                             },
    energy: 1,                                 energy: 100,
    eat: function(){                           attack: function(target){
        this.energy++;                            this.energy = this.energy - 5;
    }                                             target.isAlive = false;
});                                            }
                                             });


                           var bob = new Human('Bob', 25);
Extending Classes
var Human = new Class({                      var Ninja = new Class({
    initialize: function(name, age){           Extends: Human,
        this.name = name;                      initialize: function(side, name, age){
        this.age = age;                           this.side = side;
    },                                            this.parent(name, age);
    isAlive: true,                             },
    energy: 1,                                 energy: 100,
    eat: function(){                           attack: function(target){
        this.energy++;                            this.energy = this.energy - 5;
    }                                             target.isAlive = false;
});                                            }
                                             });


                           var bob = new Human('Bob', 25);


                          var blackNinja =
                            new Ninja('evil', 'Nin Tendo', 'unknown');
                          //blackNinja.isAlive = true
                          //blackNinja.name = 'Nin Tendo'

                          blackNinja.attack(bob);
                          //bob never had a chance
Implementing Classes
Implementing Classes
var Human = new Class({
  initialize: function(name, age){
     this.name = name;
     this.age = age;
  },
  isAlive: true,
  energy: 1,
  eat: function(){
     this.energy++;
  }
});
Implementing Classes
var Human = new Class({
  initialize: function(name, age){
     this.name = name;
     this.age = age;
  },
  isAlive: true,
  energy: 1,
  eat: function(){
     this.energy++;
  }
});

var Warrior = new Class({
  energy: 100,
  kills: 0,
  attack: function(target){
    if (target.energy < this.energy) {
       target.isAlive = false;
       this.kills++;
    }
    this.energy = this.energy - 5;
  }
});
Implementing Classes
var Human = new Class({                  var Ninja = new Class({
  initialize: function(name, age){         Extends: Human,
     this.name = name;                     Implements: [Warrior],
     this.age = age;                       initialize: function(side, name, age){
  },                                         this.side = side;
  isAlive: true,                             this.parent(name, age);
  energy: 1,                               }
  eat: function(){                       });
     this.energy++;
  }
});

var Warrior = new Class({                var Samurai = new Class({
  energy: 100,                             Extends: Human,
  kills: 0,                                Implements: [Warrior],
  attack: function(target){                side: 'good',
    if (target.energy < this.energy) {     energy: 1000
       target.isAlive = false;           });
       this.kills++;
    }
    this.energy = this.energy - 5;
  }
});
When to write a class...
When to write a class...
When to write a class...
When to write a class...
When to write a class...
Key Aspects of JS Classes
Key Aspects of JS Classes
• Shallow inheritance works best.
Key Aspects of JS Classes
• Shallow inheritance works best.
• Break up logic into small methods.
Key Aspects of JS Classes
• Shallow inheritance works best.
• Break up logic into small methods.
• Break up functionality into small classes.
Key Aspects of JS Classes
• Shallow inheritance works best.
• Break up logic into small methods.
• Break up functionality into small classes.
• Build ‘controller’ classes for grouped
 functionality.
Key Aspects of JS Classes
• Shallow inheritance works best.
• Break up logic into small methods.
• Break up functionality into small classes.
• Build ‘controller’ classes for grouped
 functionality.

• Use options and events liberally.
Key Aspects of JS Classes
• Shallow inheritance works best.
• Break up logic into small methods.
• Break up functionality into small classes.
• Build ‘controller’ classes for grouped
  functionality.

• Use options and events liberally.
• Don’t be afraid to refactor, but avoid
  breaking the interface.
Let’s look at that earlier example again
...
<script>
$(‘myForm’).addEvent(‘submit’, function(evt){
  evt.preventDefault();
  this.send({
      onComplete: function(result){ ... },
      update: $(‘myContainer’)
  });
});
</script>
Program a Pattern
var FormUpdater = new Class({
  initialize: function(form, container, options) {
    this.form = $(form);
    this.container = $(container);
    this.request = new Request(options);
    this.attach();
  },
  attach: function(){
    this.form.addEvent(‘submit’,
      this.send.bind(this));
  },
  send: function(evt){
    if (evt) evt.preventDefault();
    this.request.send({
      url: this.form.get(‘action’),
      onComplete: this.onComplete.bind(this)
    });
  },
  onComplete: function(responseTxt){
      this.container.set(‘html’, responseTxt);
  }
});
new FormUpdater($(‘myForm’), $(‘myContainer’));
...and then extend it
var FormUpdater.Append = new Class({
 Extends: FormUpdater,
 onComplete: function(responseTxt){
    this.container.adopt(
      new Element(‘div’, {html: responseTxt})
    );
 }
});
new FormUpdater.Append($(‘myForm’), $(‘myTarget’));
How I write now
How I write now
var myApp = {
  init: function(){
   myApp.apples()                      Classes
   myApp.orange()                      DatePicker
   myApp.lemons()                     FormValidator
 },                                         Fx
 apples: function(){                     Request
   new AppleGroup($$(‘div.apple’));     Slideshow
 },                                       Apple
 orange: function(){                   AppleGroup
   new Orange($(‘orange’)                Orange
 },                                        etc...
  etc...
How I write now
var myApp = {
  init: function(){
   myApp.apples()                              Classes
   myApp.orange()                             DatePicker
   myApp.lemons()                            FormValidator
 },                                                Fx
 apples: function(){                            Request
   new AppleGroup($$(‘div.apple’));            Slideshow
 },                                              Apple
 orange: function(){                          AppleGroup
   new Orange($(‘orange’)                       Orange
 },                                               etc...
  etc...




                  I write as little of this as possible
Pros
• Small, reusable, readable, generic classes
• Only the variables are managed in a specific application
• The footprint between a specific app and your generic
  codebase is as small as possible - only instantiation calls
Pros
• Small, reusable, readable, generic classes
• Only the variables are managed in a specific application
• The footprint between a specific app and your generic
  codebase is as small as possible - only instantiation calls



                      & Cons
• Requires a bit more skill.
• Can often mean more bytes of code in the short term.
• Test driven development is a must.
I use MooTools
I use MooTools
• MooTools makes JavaScript easier (as do
 all frameworks).
I use MooTools
• MooTools makes JavaScript easier (as do
 all frameworks).

• It encourages you to reuse your work, and
 to write your code to be flexible for future
 use.
I use MooTools
• MooTools makes JavaScript easier (as do
 all frameworks).

• It encourages you to reuse your work, and
 to write your code to be flexible for future
 use.

• It is designed to be extended.
I use MooTools
• MooTools makes JavaScript easier (as do
 all frameworks).

• It encourages you to reuse your work, and
 to write your code to be flexible for future
 use.

• It is designed to be extended.
• These are qualities of JavaScript really;
 MooTools just makes the interface more
 accessible.

More Related Content

What's hot

About java
About javaAbout java
About javaJay Xu
 
かとうの Kotlin 講座 こってり版
かとうの Kotlin 講座 こってり版かとうの Kotlin 講座 こってり版
かとうの Kotlin 講座 こってり版Yutaka Kato
 
深入浅出Jscex
深入浅出Jscex深入浅出Jscex
深入浅出Jscexjeffz
 
Kotlin on Android: Delegate with pleasure
Kotlin on Android: Delegate with pleasureKotlin on Android: Delegate with pleasure
Kotlin on Android: Delegate with pleasureDmytro Zaitsev
 
Scala for Java programmers
Scala for Java programmersScala for Java programmers
Scala for Java programmers輝 子安
 
SWDC 2010: Programming to Patterns
SWDC 2010: Programming to PatternsSWDC 2010: Programming to Patterns
SWDC 2010: Programming to Patternsdylanks
 
Introduction To Scala
Introduction To ScalaIntroduction To Scala
Introduction To ScalaInnar Made
 

What's hot (15)

1.2 scala basics
1.2 scala basics1.2 scala basics
1.2 scala basics
 
обзор Python
обзор Pythonобзор Python
обзор Python
 
About java
About javaAbout java
About java
 
かとうの Kotlin 講座 こってり版
かとうの Kotlin 講座 こってり版かとうの Kotlin 講座 こってり版
かとうの Kotlin 講座 こってり版
 
Scala in practice
Scala in practiceScala in practice
Scala in practice
 
JavaYDL11
JavaYDL11JavaYDL11
JavaYDL11
 
Hammurabi
HammurabiHammurabi
Hammurabi
 
A bit about Scala
A bit about ScalaA bit about Scala
A bit about Scala
 
深入浅出Jscex
深入浅出Jscex深入浅出Jscex
深入浅出Jscex
 
Scala for Jedi
Scala for JediScala for Jedi
Scala for Jedi
 
Kotlin on Android: Delegate with pleasure
Kotlin on Android: Delegate with pleasureKotlin on Android: Delegate with pleasure
Kotlin on Android: Delegate with pleasure
 
Scala for Java programmers
Scala for Java programmersScala for Java programmers
Scala for Java programmers
 
JavaYDL6
JavaYDL6JavaYDL6
JavaYDL6
 
SWDC 2010: Programming to Patterns
SWDC 2010: Programming to PatternsSWDC 2010: Programming to Patterns
SWDC 2010: Programming to Patterns
 
Introduction To Scala
Introduction To ScalaIntroduction To Scala
Introduction To Scala
 

Similar to Programming To Patterns

Javascript best practices
Javascript best practicesJavascript best practices
Javascript best practicesManav Gupta
 
2.1 recap from-day_one
2.1 recap from-day_one2.1 recap from-day_one
2.1 recap from-day_onefuturespective
 
Shibuya.js Lightning Talks
Shibuya.js Lightning TalksShibuya.js Lightning Talks
Shibuya.js Lightning Talksjeresig
 
FITC CoffeeScript 101
FITC CoffeeScript 101FITC CoffeeScript 101
FITC CoffeeScript 101Faisal Abid
 
CoffeeScript
CoffeeScriptCoffeeScript
CoffeeScriptNone
 
OO JS for AS3 Devs
OO JS for AS3 DevsOO JS for AS3 Devs
OO JS for AS3 DevsJason Hanson
 
Having a problem figuring out where my errors are- The code is not run.pdf
Having a problem figuring out where my errors are- The code is not run.pdfHaving a problem figuring out where my errors are- The code is not run.pdf
Having a problem figuring out where my errors are- The code is not run.pdfNicholasflqStewartl
 
Idiomatic Kotlin
Idiomatic KotlinIdiomatic Kotlin
Idiomatic Kotlinintelliyole
 
srcArtifact.javasrcArtifact.javaclassArtifactextendsCave{pub.docx
srcArtifact.javasrcArtifact.javaclassArtifactextendsCave{pub.docxsrcArtifact.javasrcArtifact.javaclassArtifactextendsCave{pub.docx
srcArtifact.javasrcArtifact.javaclassArtifactextendsCave{pub.docxwhitneyleman54422
 
Unit testing with PHPUnit
Unit testing with PHPUnitUnit testing with PHPUnit
Unit testing with PHPUnitferca_sl
 
CodeCamp Iasi 10 march 2012 - Practical Groovy
CodeCamp Iasi 10 march 2012 - Practical GroovyCodeCamp Iasi 10 march 2012 - Practical Groovy
CodeCamp Iasi 10 march 2012 - Practical GroovyCodecamp Romania
 
JavaScript Classes and Inheritance
JavaScript Classes and InheritanceJavaScript Classes and Inheritance
JavaScript Classes and Inheritancemarcheiligers
 
Learning Functional Programming Without Growing a Neckbeard
Learning Functional Programming Without Growing a NeckbeardLearning Functional Programming Without Growing a Neckbeard
Learning Functional Programming Without Growing a NeckbeardKelsey Gilmore-Innis
 
Design patterns in javascript
Design patterns in javascriptDesign patterns in javascript
Design patterns in javascriptMiao Siyu
 
javascript prototype
javascript prototypejavascript prototype
javascript prototypeHika Maeng
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScriptJulie Iskander
 

Similar to Programming To Patterns (20)

Javascript best practices
Javascript best practicesJavascript best practices
Javascript best practices
 
2.1 recap from-day_one
2.1 recap from-day_one2.1 recap from-day_one
2.1 recap from-day_one
 
Shibuya.js Lightning Talks
Shibuya.js Lightning TalksShibuya.js Lightning Talks
Shibuya.js Lightning Talks
 
Scala 2013 review
Scala 2013 reviewScala 2013 review
Scala 2013 review
 
FITC CoffeeScript 101
FITC CoffeeScript 101FITC CoffeeScript 101
FITC CoffeeScript 101
 
CoffeeScript
CoffeeScriptCoffeeScript
CoffeeScript
 
OO JS for AS3 Devs
OO JS for AS3 DevsOO JS for AS3 Devs
OO JS for AS3 Devs
 
Having a problem figuring out where my errors are- The code is not run.pdf
Having a problem figuring out where my errors are- The code is not run.pdfHaving a problem figuring out where my errors are- The code is not run.pdf
Having a problem figuring out where my errors are- The code is not run.pdf
 
Idiomatic Kotlin
Idiomatic KotlinIdiomatic Kotlin
Idiomatic Kotlin
 
srcArtifact.javasrcArtifact.javaclassArtifactextendsCave{pub.docx
srcArtifact.javasrcArtifact.javaclassArtifactextendsCave{pub.docxsrcArtifact.javasrcArtifact.javaclassArtifactextendsCave{pub.docx
srcArtifact.javasrcArtifact.javaclassArtifactextendsCave{pub.docx
 
Lecture33
Lecture33Lecture33
Lecture33
 
Scala
ScalaScala
Scala
 
Unit testing with PHPUnit
Unit testing with PHPUnitUnit testing with PHPUnit
Unit testing with PHPUnit
 
CodeCamp Iasi 10 march 2012 - Practical Groovy
CodeCamp Iasi 10 march 2012 - Practical GroovyCodeCamp Iasi 10 march 2012 - Practical Groovy
CodeCamp Iasi 10 march 2012 - Practical Groovy
 
25-functions.ppt
25-functions.ppt25-functions.ppt
25-functions.ppt
 
JavaScript Classes and Inheritance
JavaScript Classes and InheritanceJavaScript Classes and Inheritance
JavaScript Classes and Inheritance
 
Learning Functional Programming Without Growing a Neckbeard
Learning Functional Programming Without Growing a NeckbeardLearning Functional Programming Without Growing a Neckbeard
Learning Functional Programming Without Growing a Neckbeard
 
Design patterns in javascript
Design patterns in javascriptDesign patterns in javascript
Design patterns in javascript
 
javascript prototype
javascript prototypejavascript prototype
javascript prototype
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScript
 

Recently uploaded

20230202 - Introduction to tis-py
20230202 - Introduction to tis-py20230202 - Introduction to tis-py
20230202 - Introduction to tis-pyJamie (Taka) Wang
 
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
 
VoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBXVoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBXTarek Kalaji
 
Comparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioComparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioChristian Posta
 
COMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online CollaborationCOMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online Collaborationbruanjhuli
 
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
 
How Accurate are Carbon Emissions Projections?
How Accurate are Carbon Emissions Projections?How Accurate are Carbon Emissions Projections?
How Accurate are Carbon Emissions Projections?IES VE
 
Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024SkyPlanner
 
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
 
Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )Brian Pichman
 
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
 
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
 
Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Commit University
 
Designing A Time bound resource download URL
Designing A Time bound resource download URLDesigning A Time bound resource download URL
Designing A Time bound resource download URLRuncy Oommen
 
Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1DianaGray10
 
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
 
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
 

Recently uploaded (20)

20230202 - Introduction to tis-py
20230202 - Introduction to tis-py20230202 - Introduction to tis-py
20230202 - Introduction to tis-py
 
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.
 
VoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBXVoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBX
 
Comparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioComparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and Istio
 
COMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online CollaborationCOMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online Collaboration
 
20150722 - AGV
20150722 - AGV20150722 - AGV
20150722 - AGV
 
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
 
How Accurate are Carbon Emissions Projections?
How Accurate are Carbon Emissions Projections?How Accurate are Carbon Emissions Projections?
How Accurate are Carbon Emissions Projections?
 
Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024
 
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
 
Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )
 
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
 
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
 
20230104 - machine vision
20230104 - machine vision20230104 - machine vision
20230104 - machine vision
 
201610817 - edge part1
201610817 - edge part1201610817 - edge part1
201610817 - edge part1
 
Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)
 
Designing A Time bound resource download URL
Designing A Time bound resource download URLDesigning A Time bound resource download URL
Designing A Time bound resource download URL
 
Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1
 
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
 
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
 

Programming To Patterns

  • 1. Programming To Patterns
  • 2. How I used to write
  • 3. How I used to write Classes DatePicker FormValidator Fx Request Slideshow etc...
  • 4. How I used to write var myApp = { init: function(){ myApp.apples() Classes myApp.orange() DatePicker myApp.lemons() FormValidator }, Fx apples: function(){ Request $$(‘div.apple’).each(function(apple) { Slideshow var form = apple.getElement(‘form’); etc... form.addEvent(‘submit’, funciton(event){ ....}); }); }, orange: function(){ $(‘orange’).getElements(‘li’).each... }, etc...
  • 5. How I used to write var myApp = { init: function(){ myApp.apples() Classes myApp.orange() DatePicker myApp.lemons() FormValidator }, Fx apples: function(){ Request $$(‘div.apple’).each(function(apple) { Slideshow var form = apple.getElement(‘form’); etc... form.addEvent(‘submit’, funciton(event){ ....}); }); }, orange: function(){ $(‘orange’).getElements(‘li’).each... }, etc... This tends to get out of hand
  • 6. Banging it out... <script> window.addEvent(‘domready’, function(){ $(‘myForm’).addEvent(‘submit’, function(evt){ evt.preventDefault(); this.send({ onComplete: function(result){ ... }, update: $(‘myContainer’) }); }); }); </script> This is very tempting.
  • 7. Pros • Writing the logic for a specific app is fast and furious • The test environment is the app
  • 8. Pros • Writing the logic for a specific app is fast and furious • The test environment is the app & Cons • It’s much harder to maintain • A high percentage of code you write for the app isn’t reusable
  • 10. Using Classes This is how MooTools does it var Human = new Class({ isAlive: true, energy: 1, eat: function(){ this.energy++; } }); Human
  • 11. Using Classes This is how MooTools does it var Human = new Class({ isAlive: true, energy: 1, eat: function(){ this.energy++; } }); var bob = new Human(); //bob.energy === 1 bob.eat(); //bob.energy === 2 Human bob
  • 13. Extending Classes var Human = new Class({ initialize: function(name, age){ this.name = name; this.age = age; }, isAlive: true, energy: 1, eat: function(){ this.energy++; } });
  • 14. Extending Classes var Human = new Class({ var Ninja = new Class({ initialize: function(name, age){ Extends: Human, this.name = name; initialize: function(side, name, age){ this.age = age; this.side = side; }, this.parent(name, age); isAlive: true, }, energy: 1, energy: 100, eat: function(){ attack: function(target){ this.energy++; this.energy = this.energy - 5; } target.isAlive = false; }); } });
  • 15. Extending Classes var Human = new Class({ var Ninja = new Class({ initialize: function(name, age){ Extends: Human, this.name = name; initialize: function(side, name, age){ this.age = age; this.side = side; }, this.parent(name, age); isAlive: true, }, energy: 1, energy: 100, eat: function(){ attack: function(target){ this.energy++; this.energy = this.energy - 5; } target.isAlive = false; }); } });
  • 16. Extending Classes var Human = new Class({ var Ninja = new Class({ initialize: function(name, age){ Extends: Human, this.name = name; initialize: function(side, name, age){ this.age = age; this.side = side; }, this.parent(name, age); isAlive: true, }, energy: 1, energy: 100, eat: function(){ attack: function(target){ this.energy++; this.energy = this.energy - 5; } target.isAlive = false; }); } }); var bob = new Human('Bob', 25);
  • 17. Extending Classes var Human = new Class({ var Ninja = new Class({ initialize: function(name, age){ Extends: Human, this.name = name; initialize: function(side, name, age){ this.age = age; this.side = side; }, this.parent(name, age); isAlive: true, }, energy: 1, energy: 100, eat: function(){ attack: function(target){ this.energy++; this.energy = this.energy - 5; } target.isAlive = false; }); } }); var bob = new Human('Bob', 25); var blackNinja = new Ninja('evil', 'Nin Tendo', 'unknown'); //blackNinja.isAlive = true //blackNinja.name = 'Nin Tendo' blackNinja.attack(bob); //bob never had a chance
  • 19. Implementing Classes var Human = new Class({ initialize: function(name, age){ this.name = name; this.age = age; }, isAlive: true, energy: 1, eat: function(){ this.energy++; } });
  • 20. Implementing Classes var Human = new Class({ initialize: function(name, age){ this.name = name; this.age = age; }, isAlive: true, energy: 1, eat: function(){ this.energy++; } }); var Warrior = new Class({ energy: 100, kills: 0, attack: function(target){ if (target.energy < this.energy) { target.isAlive = false; this.kills++; } this.energy = this.energy - 5; } });
  • 21. Implementing Classes var Human = new Class({ var Ninja = new Class({ initialize: function(name, age){ Extends: Human, this.name = name; Implements: [Warrior], this.age = age; initialize: function(side, name, age){ }, this.side = side; isAlive: true, this.parent(name, age); energy: 1, } eat: function(){ }); this.energy++; } }); var Warrior = new Class({ var Samurai = new Class({ energy: 100, Extends: Human, kills: 0, Implements: [Warrior], attack: function(target){ side: 'good', if (target.energy < this.energy) { energy: 1000 target.isAlive = false; }); this.kills++; } this.energy = this.energy - 5; } });
  • 22. When to write a class...
  • 23. When to write a class...
  • 24. When to write a class...
  • 25. When to write a class...
  • 26. When to write a class...
  • 27. Key Aspects of JS Classes
  • 28. Key Aspects of JS Classes • Shallow inheritance works best.
  • 29. Key Aspects of JS Classes • Shallow inheritance works best. • Break up logic into small methods.
  • 30. Key Aspects of JS Classes • Shallow inheritance works best. • Break up logic into small methods. • Break up functionality into small classes.
  • 31. Key Aspects of JS Classes • Shallow inheritance works best. • Break up logic into small methods. • Break up functionality into small classes. • Build ‘controller’ classes for grouped functionality.
  • 32. Key Aspects of JS Classes • Shallow inheritance works best. • Break up logic into small methods. • Break up functionality into small classes. • Build ‘controller’ classes for grouped functionality. • Use options and events liberally.
  • 33. Key Aspects of JS Classes • Shallow inheritance works best. • Break up logic into small methods. • Break up functionality into small classes. • Build ‘controller’ classes for grouped functionality. • Use options and events liberally. • Don’t be afraid to refactor, but avoid breaking the interface.
  • 34. Let’s look at that earlier example again ... <script> $(‘myForm’).addEvent(‘submit’, function(evt){ evt.preventDefault(); this.send({ onComplete: function(result){ ... }, update: $(‘myContainer’) }); }); </script>
  • 35. Program a Pattern var FormUpdater = new Class({ initialize: function(form, container, options) { this.form = $(form); this.container = $(container); this.request = new Request(options); this.attach(); }, attach: function(){ this.form.addEvent(‘submit’, this.send.bind(this)); }, send: function(evt){ if (evt) evt.preventDefault(); this.request.send({ url: this.form.get(‘action’), onComplete: this.onComplete.bind(this) }); }, onComplete: function(responseTxt){ this.container.set(‘html’, responseTxt); } }); new FormUpdater($(‘myForm’), $(‘myContainer’));
  • 36. ...and then extend it var FormUpdater.Append = new Class({ Extends: FormUpdater, onComplete: function(responseTxt){ this.container.adopt( new Element(‘div’, {html: responseTxt}) ); } }); new FormUpdater.Append($(‘myForm’), $(‘myTarget’));
  • 37. How I write now
  • 38. How I write now var myApp = { init: function(){ myApp.apples() Classes myApp.orange() DatePicker myApp.lemons() FormValidator }, Fx apples: function(){ Request new AppleGroup($$(‘div.apple’)); Slideshow }, Apple orange: function(){ AppleGroup new Orange($(‘orange’) Orange }, etc... etc...
  • 39. How I write now var myApp = { init: function(){ myApp.apples() Classes myApp.orange() DatePicker myApp.lemons() FormValidator }, Fx apples: function(){ Request new AppleGroup($$(‘div.apple’)); Slideshow }, Apple orange: function(){ AppleGroup new Orange($(‘orange’) Orange }, etc... etc... I write as little of this as possible
  • 40. Pros • Small, reusable, readable, generic classes • Only the variables are managed in a specific application • The footprint between a specific app and your generic codebase is as small as possible - only instantiation calls
  • 41. Pros • Small, reusable, readable, generic classes • Only the variables are managed in a specific application • The footprint between a specific app and your generic codebase is as small as possible - only instantiation calls & Cons • Requires a bit more skill. • Can often mean more bytes of code in the short term. • Test driven development is a must.
  • 43. I use MooTools • MooTools makes JavaScript easier (as do all frameworks).
  • 44. I use MooTools • MooTools makes JavaScript easier (as do all frameworks). • It encourages you to reuse your work, and to write your code to be flexible for future use.
  • 45. I use MooTools • MooTools makes JavaScript easier (as do all frameworks). • It encourages you to reuse your work, and to write your code to be flexible for future use. • It is designed to be extended.
  • 46. I use MooTools • MooTools makes JavaScript easier (as do all frameworks). • It encourages you to reuse your work, and to write your code to be flexible for future use. • It is designed to be extended. • These are qualities of JavaScript really; MooTools just makes the interface more accessible.