SlideShare uma empresa Scribd logo
1 de 27
Baixar para ler offline
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?

Mais conteúdo relacionado

Mais procurados

Javascript and Jquery Best practices
Javascript and Jquery Best practicesJavascript and Jquery Best practices
Javascript and Jquery Best practicesSultan Khan
 
Intro to JavaScript
Intro to JavaScriptIntro to JavaScript
Intro to JavaScriptYakov Fain
 
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 & UXJWORKS powered by Ordina
 
Javascript Module Patterns
Javascript Module PatternsJavascript Module Patterns
Javascript Module PatternsNicholas Jansma
 
Java script tutorial
Java script tutorialJava script tutorial
Java script tutorialDoeun KOCH
 
JavaScript Modules Done Right
JavaScript Modules Done RightJavaScript Modules Done Right
JavaScript Modules Done RightMariusz Nowak
 
Dart for Java Developers
Dart for Java DevelopersDart for Java Developers
Dart for Java DevelopersYakov Fain
 
Workshop 12: AngularJS Parte I
Workshop 12: AngularJS Parte IWorkshop 12: AngularJS Parte I
Workshop 12: AngularJS Parte IVisual Engineering
 
Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Librariesjeresig
 
JavaScript Library Overview
JavaScript Library OverviewJavaScript Library Overview
JavaScript Library Overviewjeresig
 
AngularJS Basics
AngularJS BasicsAngularJS Basics
AngularJS BasicsRavi Mone
 
Ten useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesTen useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesAnkit Rastogi
 
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 AppsMike Subelsky
 
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 OrientDBApaichon Punopas
 
Javascript basics for automation testing
Javascript  basics for automation testingJavascript  basics for automation testing
Javascript basics for automation testingVikas Thange
 

Mais procurados (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
 

Destaque

Architektura ngrx w angular 2+
Architektura ngrx w angular 2+Architektura ngrx w angular 2+
Architektura ngrx w angular 2+Paweł Żurowski
 
AngularJS Introduction
AngularJS IntroductionAngularJS Introduction
AngularJS IntroductionCarlos Morales
 
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 1Kevin Meade
 
Oracle Performance Tuning Fundamentals
Oracle Performance Tuning FundamentalsOracle Performance Tuning Fundamentals
Oracle Performance Tuning FundamentalsCarlos Sierra
 
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 developersPaweł Żurowski
 
Introduction to Angular 2
Introduction to Angular 2Introduction to Angular 2
Introduction to Angular 2Knoldus Inc.
 
Getting Started with Angular 2
Getting Started with Angular 2Getting Started with Angular 2
Getting Started with Angular 2FITC
 
Brazilian protests – June 2013
Brazilian protests – June 2013Brazilian protests – June 2013
Brazilian protests – June 2013Luciana Viter
 
Wix Application Framework
Wix Application FrameworkWix Application Framework
Wix Application FrameworkRan Mizrahi
 
Ran Mizrahi - Symfony2 meets Drupal8
Ran Mizrahi - Symfony2 meets Drupal8Ran Mizrahi - Symfony2 meets Drupal8
Ran Mizrahi - Symfony2 meets Drupal8Ran Mizrahi
 
00 are you free - taxis
00   are you free - taxis00   are you free - taxis
00 are you free - taxisLuciana 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 2007Dan Foster
 
Merkatu ikerketa-Irutxuloko Hitza
Merkatu ikerketa-Irutxuloko HitzaMerkatu ikerketa-Irutxuloko Hitza
Merkatu ikerketa-Irutxuloko HitzaItxaso Ferreras
 
Rochelle Michalek
Rochelle MichalekRochelle Michalek
Rochelle Michalekjlandsman
 
Reading Revolution Blogs
Reading Revolution BlogsReading Revolution Blogs
Reading Revolution BlogsLaurie Fowler
 
The Pmarca Blog Archives
The Pmarca Blog ArchivesThe Pmarca Blog Archives
The Pmarca Blog ArchivesRazin Mustafiz
 
"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...Jenni Lloyd
 

Destaque (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...
 

Semelhante a How Angular Embraced Traditional OOP Design Patterns

HTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyDavid Padbury
 
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 - Chapter 7 - Advanced Functions
 JavaScript - Chapter 7 - Advanced Functions JavaScript - Chapter 7 - Advanced Functions
JavaScript - Chapter 7 - Advanced FunctionsWebStackAcademy
 
JavaScript Fundamentals & JQuery
JavaScript Fundamentals & JQueryJavaScript Fundamentals & JQuery
JavaScript Fundamentals & JQueryJamshid Hashimi
 
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 UmbracoAndy Butland
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing UpDavid Padbury
 
Modular javascript
Modular javascriptModular javascript
Modular javascriptZain Shaikh
 
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 PovolnyManageIQ
 
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 2018Loiane Groner
 
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)Daniel Bryant
 
Patterns Are Good For Managers
Patterns Are Good For ManagersPatterns Are Good For Managers
Patterns Are Good For ManagersAgileThought
 
Javascript coding-and-design-patterns
Javascript coding-and-design-patternsJavascript coding-and-design-patterns
Javascript coding-and-design-patternsHernan Mammana
 
Smoothing Your Java with DSLs
Smoothing Your Java with DSLsSmoothing Your Java with DSLs
Smoothing Your Java with DSLsintelliyole
 
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 applicationsDivyanshGupta922023
 
AngularJS Architecture
AngularJS ArchitectureAngularJS Architecture
AngularJS ArchitectureEyal Vardi
 

Semelhante a How Angular Embraced Traditional OOP 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
 

Último

The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
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...Martijn de Jong
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
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 WorkerThousandEyes
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 

Último (20)

The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
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...
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
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
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 

How Angular Embraced Traditional OOP 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... }];