SlideShare une entreprise Scribd logo
1  sur  27
Télécharger pour lire hors ligne
How Angular Embraced
Traditional OOP Design
Patterns

Ran Mizrahi (@ranm8)

Open Source Dpt. Leader @ CodeOasis
About CodeOasis

•
•
•
•

CodeOasis specializes in cutting-edge web solutions.

!

Large variety of customers (from startups to enterprises).

!

We’re passionate about JavaScript (-:

!

Technologies we love:


•
•
•
•
•
•

!

Play Framework

AngularJS 

nodeJS 

HTML5

CSS3

!

Our Microsoft department works with C#, WPF, etc.
Implementing
Design Patterns in
JavaScript
Implementing Design Patterns in JavaScript
Most traditional object-oriented languages

•
•
•
•
•

Classes.

!

Interfaces.

!

Inheritance.

!

Encapsulation.

!

Polymorphism.
Implementing Design Patterns in JavaScript
We don’t have classes…
var User = new Class({
initialize: function(name) {
this.name = name;
},
setEmail: function(mail) {
this.mail = mail;
}
});
!
var someUser = new User('Ran Mizrahi');
* MooTools Example
Implementing Design Patterns in JavaScript
We don’t have interfaces…

var DynamicMap = new Interface('DynamicMap', ['centerOnPoint', 'zoom',
'draw']);

!

function displayRoute(mapInstance) {
Interface.ensureImplements(mapInstance, DynamicMap);

!

mapInstace.centerOnPoint(12, 34);
mapInstace.draw(5);
mapInstace.zoom();
}
* Taken from the book “Pro JavaScript Design Patterns”
Implementing Design Patterns in JavaScript
We don’t have classical inheritance..
var User = new Class({
!
extends: BaseUser,
initialize: function(name) {
this.name = name;
},
setEmail: function(mail) {
this.mail = mail;
}
});
!
var someUser = new User('Ran Mizrahi');
* MooTools Example
Stop Forcing It!
Embrace It!
Learning To Embrace JavaScript

“When I see a bird that walks
like a duck and sounds like a
duck, I call that bird a duck”
— James Whitcomb Riley
Learning To Embrace JavaScript

This is how a duck looks like…

function isWindow(obj) {
return obj && obj.document && obj.location
&& obj.alert && obj.setInterval;
}
* Angular implementation of the isWindow method…
Learning To Embrace JavaScript
JavaScript is simple (can be explained over a beer) and
makes us write less code…
Java:!
  List<Book> books = new ArrayList<Book>();!

!

JavaScript:!
  var books = [];!
Learning To Embrace JavaScript
Object is a unit responsible for state and behaviour and
JavaScript function has them both.
function Unit() {
var state;
!
function behaviour() {
// Some behaviour
}

}

return function() {
// Do something
}
Learning To Embrace JavaScript
We don’t have visibility keywords (e.g. private, protected,
public) but we do have closures
var Service = (function(window, undefined) {
// Private
function base64Encode(string) {
return window.btoa(string);
}
// Public
return {
encode: function(string) {
return base64Encode(string);
}
};
}(window));
Learning To Embrace JavaScript
State management can be as easy by using constructor
functions or closures…
function someFunction(baseUrl) {
var config = {
url: baseUrl
};

};

return function() {
return config.url + '/hey';
}

function Duck(name) {
// Object state
this.name = name;
}
Learning To Embrace JavaScript
Polymorphism can be beautiful without interfaces, if it’s just a
duck…
function Duck() {
// Private state here…

!

function Bird() {
// Private state here…

!

// Public state
return {
walk: function() {
// Walk like a duck
return quack();
},

// Public state
return {
walk: function() {
// Walk like a bird
return tweet();
},

talk: function() {
// Talk like a duck
}

talk: function() {
// Talk like a bird
}

};
}

};
}
function talker(someBird) {
// Make it talk
someBird.talk();
}
Learning To Embrace JavaScript
But what will happen if the duck won’t talk…

JavaScript has prototypical inheritance but yet, I don’t often
feel I need to inherit anything (prefer polymorphic composition
over inheritance).
Learning To Embrace JavaScript
For true coverage and confidence, compilers won’t do the job
and they can’t replace real unit test coverage.

•
•
•

Almost everything is mutable.

!

Easily stub anything.

!

Easily fake dependencies.
Design Patterns in
AngularJS
MVC and Controllers
angular.module('myModule')
.controller('MyCtrl', ['$http', MyCtrl]);
!
// Dependencies are in closure (-:
function MyCtrl($http) {
var someState = {};

}

function doSomething() {
// Closure is accessible.
}

•

Controllers are just JavaScript function. 


•

They can encapsulate and preserve state by using closures.


•

!

Exposes behaviour with $scope.
Dependency Injection
angular.module('myModule')
.controller('MyCtrl', ['$http', MyCtrl]);
function MyCtrl($http) {
$http.get('http://google.com').then(getTheMonkey);
}

•

Simple dynamic dependency injection based on arrays and
naming convention. 


•

Makes your code polymorphic by easily replacing your
implementation.


•

!

Super easy to isolate and test.
Decorator
Decorator is a pattern used to “decorate” functionality of
certain object.
Decorator
Angular made service decoration really easy…
$provider.decorator('$log', ['delegate', function(delegate) {
// Convert warning to error
delegate.warn = delegate.error;
// Return the decorated service
return delegate;
}]);

Ask for a function, manipulate it and return a new one (-:
Facade
A facade is an object that provides a simplified interface to a
larger body of code and logic.
angular.module('myModule')
.factory('ReallyComplicatedService', [Service]);

!

function Service($http) {
// Do all the private stuff and handle the other library
// Expose really simple interface
return {
get: function() {
// Get it
},
del: function() {
// Delete it
}
};
}
Singleton
Singletons is a design pattern that restricts the instantiation of
a class to one object.
var Singleton = (function() {
function privateFunction() {
// Do private stuff
}
return {
someMethod: function() {
// Do public stuff
},
anotherMethod: function() {
// Do some more public stuff
}

};
}());

JavaScript makes singleton really easy (-: 

But still, it’s global and hard to configure…
Singleton
Angular used it and provided us with dependency injection to
avoid singleton downsides among others.
angular.module('myModule')
.provider('myHttp', myHttp);
function myHttp() {
var baseUrl;
this.baseUrl = function(value) {
if (!value) {
return baseUrl;
}
};

}

baseUrl = value;

this.$get = ['$q', function() {
// myHttp service implementation...
}];
Thank you!

Questions?

Contenu connexe

Tendances

Tendances (20)

Javascript and Jquery Best practices
Javascript and Jquery Best practicesJavascript and Jquery Best practices
Javascript and Jquery Best practices
 
Intro to JavaScript
Intro to JavaScriptIntro to JavaScript
Intro to JavaScript
 
JavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UXJavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UX
 
Angularjs
AngularjsAngularjs
Angularjs
 
Javascript Module Patterns
Javascript Module PatternsJavascript Module Patterns
Javascript Module Patterns
 
Java script tutorial
Java script tutorialJava script tutorial
Java script tutorial
 
JavaScript Modules Done Right
JavaScript Modules Done RightJavaScript Modules Done Right
JavaScript Modules Done Right
 
Dart for Java Developers
Dart for Java DevelopersDart for Java Developers
Dart for Java Developers
 
Workshop 12: AngularJS Parte I
Workshop 12: AngularJS Parte IWorkshop 12: AngularJS Parte I
Workshop 12: AngularJS Parte I
 
Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Libraries
 
JavaScript Library Overview
JavaScript Library OverviewJavaScript Library Overview
JavaScript Library Overview
 
AngularJS Basics
AngularJS BasicsAngularJS Basics
AngularJS Basics
 
Ten useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesTen useful JavaScript tips & best practices
Ten useful JavaScript tips & best practices
 
SproutCore and the Future of Web Apps
SproutCore and the Future of Web AppsSproutCore and the Future of Web Apps
SproutCore and the Future of Web Apps
 
Javascript
JavascriptJavascript
Javascript
 
WEB TECHNOLOGIES JavaScript
WEB TECHNOLOGIES JavaScriptWEB TECHNOLOGIES JavaScript
WEB TECHNOLOGIES JavaScript
 
Angularjs Basics
Angularjs BasicsAngularjs Basics
Angularjs Basics
 
Lecture 5 javascript
Lecture 5 javascriptLecture 5 javascript
Lecture 5 javascript
 
Dynamic Application Development by NodeJS ,AngularJS with OrientDB
Dynamic Application Development by NodeJS ,AngularJS with OrientDBDynamic Application Development by NodeJS ,AngularJS with OrientDB
Dynamic Application Development by NodeJS ,AngularJS with OrientDB
 
Javascript basics for automation testing
Javascript  basics for automation testingJavascript  basics for automation testing
Javascript basics for automation testing
 

En vedette

Oracle SQL Performance Tuning and Optimization v26 chapter 1
Oracle SQL Performance Tuning and Optimization v26 chapter 1Oracle SQL Performance Tuning and Optimization v26 chapter 1
Oracle SQL Performance Tuning and Optimization v26 chapter 1
Kevin Meade
 
Brazilian protests – June 2013
Brazilian protests – June 2013Brazilian protests – June 2013
Brazilian protests – June 2013
Luciana Viter
 
John Mitchell Presentation Oct 08 Ppt 2007
John Mitchell Presentation Oct 08    Ppt 2007John Mitchell Presentation Oct 08    Ppt 2007
John Mitchell Presentation Oct 08 Ppt 2007
Dan Foster
 
Rochelle Michalek
Rochelle MichalekRochelle Michalek
Rochelle Michalek
jlandsman
 

En vedette (20)

Architektura ngrx w angular 2+
Architektura ngrx w angular 2+Architektura ngrx w angular 2+
Architektura ngrx w angular 2+
 
AngularJS Introduction
AngularJS IntroductionAngularJS Introduction
AngularJS Introduction
 
React 101
React 101React 101
React 101
 
Oracle SQL Performance Tuning and Optimization v26 chapter 1
Oracle SQL Performance Tuning and Optimization v26 chapter 1Oracle SQL Performance Tuning and Optimization v26 chapter 1
Oracle SQL Performance Tuning and Optimization v26 chapter 1
 
Oracle Performance Tuning Fundamentals
Oracle Performance Tuning FundamentalsOracle Performance Tuning Fundamentals
Oracle Performance Tuning Fundamentals
 
Quick introduction to Angular 4 for AngularJS 1.5 developers
Quick introduction to Angular 4 for AngularJS 1.5 developersQuick introduction to Angular 4 for AngularJS 1.5 developers
Quick introduction to Angular 4 for AngularJS 1.5 developers
 
Introduction to Angular 2
Introduction to Angular 2Introduction to Angular 2
Introduction to Angular 2
 
Getting Started with Angular 2
Getting Started with Angular 2Getting Started with Angular 2
Getting Started with Angular 2
 
Drfowlerpix
DrfowlerpixDrfowlerpix
Drfowlerpix
 
Brazilian protests – June 2013
Brazilian protests – June 2013Brazilian protests – June 2013
Brazilian protests – June 2013
 
Wix Application Framework
Wix Application FrameworkWix Application Framework
Wix Application Framework
 
Ran Mizrahi - Symfony2 meets Drupal8
Ran Mizrahi - Symfony2 meets Drupal8Ran Mizrahi - Symfony2 meets Drupal8
Ran Mizrahi - Symfony2 meets Drupal8
 
0318
03180318
0318
 
00 are you free - taxis
00   are you free - taxis00   are you free - taxis
00 are you free - taxis
 
John Mitchell Presentation Oct 08 Ppt 2007
John Mitchell Presentation Oct 08    Ppt 2007John Mitchell Presentation Oct 08    Ppt 2007
John Mitchell Presentation Oct 08 Ppt 2007
 
Merkatu ikerketa-Irutxuloko Hitza
Merkatu ikerketa-Irutxuloko HitzaMerkatu ikerketa-Irutxuloko Hitza
Merkatu ikerketa-Irutxuloko Hitza
 
Rochelle Michalek
Rochelle MichalekRochelle Michalek
Rochelle Michalek
 
Reading Revolution Blogs
Reading Revolution BlogsReading Revolution Blogs
Reading Revolution Blogs
 
The Pmarca Blog Archives
The Pmarca Blog ArchivesThe Pmarca Blog Archives
The Pmarca Blog Archives
 
"Twitter: what's all the fuss about?" / Jenni Lloyd @ Revolution Forum / Nove...
"Twitter: what's all the fuss about?" / Jenni Lloyd @ Revolution Forum / Nove..."Twitter: what's all the fuss about?" / Jenni Lloyd @ Revolution Forum / Nove...
"Twitter: what's all the fuss about?" / Jenni Lloyd @ Revolution Forum / Nove...
 

Similaire à How AngularJS Embraced Traditional Design Patterns

WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...
Fabio Franzini
 
JavaScript Fundamentals & JQuery
JavaScript Fundamentals & JQueryJavaScript Fundamentals & JQuery
JavaScript Fundamentals & JQuery
Jamshid Hashimi
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
David Padbury
 
Modular javascript
Modular javascriptModular javascript
Modular javascript
Zain Shaikh
 
Smoothing Your Java with DSLs
Smoothing Your Java with DSLsSmoothing Your Java with DSLs
Smoothing Your Java with DSLs
intelliyole
 

Similaire à How AngularJS Embraced Traditional Design Patterns (20)

HTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight Guy
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...
 
JavaScript - Chapter 7 - Advanced Functions
 JavaScript - Chapter 7 - Advanced Functions JavaScript - Chapter 7 - Advanced Functions
JavaScript - Chapter 7 - Advanced Functions
 
[2015/2016] JavaScript
[2015/2016] JavaScript[2015/2016] JavaScript
[2015/2016] JavaScript
 
Intro to Laravel 4
Intro to Laravel 4Intro to Laravel 4
Intro to Laravel 4
 
JavaScript Fundamentals & JQuery
JavaScript Fundamentals & JQueryJavaScript Fundamentals & JQuery
JavaScript Fundamentals & JQuery
 
MVC Puree - Approaches to MVC with Umbraco
MVC Puree - Approaches to MVC with UmbracoMVC Puree - Approaches to MVC with Umbraco
MVC Puree - Approaches to MVC with Umbraco
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
 
Modular javascript
Modular javascriptModular javascript
Modular javascript
 
Design Summit - UI Roadmap - Dan Clarizio, Martin Povolny
Design Summit - UI Roadmap - Dan Clarizio, Martin PovolnyDesign Summit - UI Roadmap - Dan Clarizio, Martin Povolny
Design Summit - UI Roadmap - Dan Clarizio, Martin Povolny
 
JavaScript
JavaScriptJavaScript
JavaScript
 
Angular for Java Enterprise Developers: Oracle Code One 2018
Angular for Java Enterprise Developers: Oracle Code One 2018Angular for Java Enterprise Developers: Oracle Code One 2018
Angular for Java Enterprise Developers: Oracle Code One 2018
 
MSc Enterprise Systems Development Guest Lecture at UniS (2/12/09)
MSc Enterprise Systems Development Guest Lecture at UniS (2/12/09)MSc Enterprise Systems Development Guest Lecture at UniS (2/12/09)
MSc Enterprise Systems Development Guest Lecture at UniS (2/12/09)
 
Patterns Are Good For Managers
Patterns Are Good For ManagersPatterns Are Good For Managers
Patterns Are Good For Managers
 
Javascript coding-and-design-patterns
Javascript coding-and-design-patternsJavascript coding-and-design-patterns
Javascript coding-and-design-patterns
 
AngularJS Workshop
AngularJS WorkshopAngularJS Workshop
AngularJS Workshop
 
Smoothing Your Java with DSLs
Smoothing Your Java with DSLsSmoothing Your Java with DSLs
Smoothing Your Java with DSLs
 
jquery summit presentation for large scale javascript applications
jquery summit  presentation for large scale javascript applicationsjquery summit  presentation for large scale javascript applications
jquery summit presentation for large scale javascript applications
 
AngularJS Architecture
AngularJS ArchitectureAngularJS Architecture
AngularJS Architecture
 

Dernier

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Dernier (20)

2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 

How AngularJS Embraced Traditional Design Patterns

  • 1. How Angular Embraced Traditional OOP Design Patterns Ran Mizrahi (@ranm8) Open Source Dpt. Leader @ CodeOasis
  • 2. About CodeOasis • • • • CodeOasis specializes in cutting-edge web solutions. ! Large variety of customers (from startups to enterprises). ! We’re passionate about JavaScript (-: ! Technologies we love: • • • • • • ! Play Framework AngularJS nodeJS HTML5 CSS3 ! Our Microsoft department works with C#, WPF, etc.
  • 4. Implementing Design Patterns in JavaScript Most traditional object-oriented languages • • • • • Classes. ! Interfaces. ! Inheritance. ! Encapsulation. ! Polymorphism.
  • 5. Implementing Design Patterns in JavaScript We don’t have classes… var User = new Class({ initialize: function(name) { this.name = name; }, setEmail: function(mail) { this.mail = mail; } }); ! var someUser = new User('Ran Mizrahi'); * MooTools Example
  • 6. Implementing Design Patterns in JavaScript We don’t have interfaces… var DynamicMap = new Interface('DynamicMap', ['centerOnPoint', 'zoom', 'draw']); ! function displayRoute(mapInstance) { Interface.ensureImplements(mapInstance, DynamicMap); ! mapInstace.centerOnPoint(12, 34); mapInstace.draw(5); mapInstace.zoom(); } * Taken from the book “Pro JavaScript Design Patterns”
  • 7. Implementing Design Patterns in JavaScript We don’t have classical inheritance.. var User = new Class({ ! extends: BaseUser, initialize: function(name) { this.name = name; }, setEmail: function(mail) { this.mail = mail; } }); ! var someUser = new User('Ran Mizrahi'); * MooTools Example
  • 10. Learning To Embrace JavaScript “When I see a bird that walks like a duck and sounds like a duck, I call that bird a duck” — James Whitcomb Riley
  • 11. Learning To Embrace JavaScript This is how a duck looks like… function isWindow(obj) { return obj && obj.document && obj.location && obj.alert && obj.setInterval; } * Angular implementation of the isWindow method…
  • 12. Learning To Embrace JavaScript JavaScript is simple (can be explained over a beer) and makes us write less code… Java:!   List<Book> books = new ArrayList<Book>();! ! JavaScript:!   var books = [];!
  • 13. Learning To Embrace JavaScript Object is a unit responsible for state and behaviour and JavaScript function has them both. function Unit() { var state; ! function behaviour() { // Some behaviour } } return function() { // Do something }
  • 14. Learning To Embrace JavaScript We don’t have visibility keywords (e.g. private, protected, public) but we do have closures var Service = (function(window, undefined) { // Private function base64Encode(string) { return window.btoa(string); } // Public return { encode: function(string) { return base64Encode(string); } }; }(window));
  • 15. Learning To Embrace JavaScript State management can be as easy by using constructor functions or closures… function someFunction(baseUrl) { var config = { url: baseUrl }; }; return function() { return config.url + '/hey'; } function Duck(name) { // Object state this.name = name; }
  • 16. Learning To Embrace JavaScript Polymorphism can be beautiful without interfaces, if it’s just a duck… function Duck() { // Private state here… ! function Bird() { // Private state here… ! // Public state return { walk: function() { // Walk like a duck return quack(); }, // Public state return { walk: function() { // Walk like a bird return tweet(); }, talk: function() { // Talk like a duck } talk: function() { // Talk like a bird } }; } }; } function talker(someBird) { // Make it talk someBird.talk(); }
  • 17. Learning To Embrace JavaScript But what will happen if the duck won’t talk… JavaScript has prototypical inheritance but yet, I don’t often feel I need to inherit anything (prefer polymorphic composition over inheritance).
  • 18. Learning To Embrace JavaScript For true coverage and confidence, compilers won’t do the job and they can’t replace real unit test coverage. • • • Almost everything is mutable. ! Easily stub anything. ! Easily fake dependencies.
  • 20. MVC and Controllers angular.module('myModule') .controller('MyCtrl', ['$http', MyCtrl]); ! // Dependencies are in closure (-: function MyCtrl($http) { var someState = {}; } function doSomething() { // Closure is accessible. } • Controllers are just JavaScript function. 
 • They can encapsulate and preserve state by using closures. • ! Exposes behaviour with $scope.
  • 21. Dependency Injection angular.module('myModule') .controller('MyCtrl', ['$http', MyCtrl]); function MyCtrl($http) { $http.get('http://google.com').then(getTheMonkey); } • Simple dynamic dependency injection based on arrays and naming convention. 
 • Makes your code polymorphic by easily replacing your implementation. • ! Super easy to isolate and test.
  • 22. Decorator Decorator is a pattern used to “decorate” functionality of certain object.
  • 23. Decorator Angular made service decoration really easy… $provider.decorator('$log', ['delegate', function(delegate) { // Convert warning to error delegate.warn = delegate.error; // Return the decorated service return delegate; }]); Ask for a function, manipulate it and return a new one (-:
  • 24. Facade A facade is an object that provides a simplified interface to a larger body of code and logic. angular.module('myModule') .factory('ReallyComplicatedService', [Service]); ! function Service($http) { // Do all the private stuff and handle the other library // Expose really simple interface return { get: function() { // Get it }, del: function() { // Delete it } }; }
  • 25. Singleton Singletons is a design pattern that restricts the instantiation of a class to one object. var Singleton = (function() { function privateFunction() { // Do private stuff } return { someMethod: function() { // Do public stuff }, anotherMethod: function() { // Do some more public stuff } }; }()); JavaScript makes singleton really easy (-: 
 But still, it’s global and hard to configure…
  • 26. Singleton Angular used it and provided us with dependency injection to avoid singleton downsides among others. angular.module('myModule') .provider('myHttp', myHttp); function myHttp() { var baseUrl; this.baseUrl = function(value) { if (!value) { return baseUrl; } }; } baseUrl = value; this.$get = ['$q', function() { // myHttp service implementation... }];