SlideShare a Scribd company logo
1 of 41
Download to read offline
JavaScript
Abstraction in Implementation 	

!
by Milan Adamovsky	

http://milan.adamovsky.com ◆ http://www.hardcorejs.com
Preface
• Based on personal observations	

• Spanning over 15 companies	

• Small companies to mostly enterprise	

• Not based on comprehensive research	

• Full life cycle of web development
Quick Exercise
Analyze
<html>	
<head>	
<title>	
This is the title of the page	
</title>	
</head>	
<body>	
<p id="main_content">	
This is my content	
</p>	
<ul>	
<li class="first"> One	
<li> Two	
<ol>	
<li class="first"> A	
</ol>	
<li>	
</ul>	
</body>	
</html>
Analysis
• A document	

• A tree of hierarchal nodes off of root node	

• Two children nodes off of root node	

• Second child node has two children nodes	

• Two children nodes are siblings
Overview
• Ultimate goal is to write less code	

• Increase reusability	

• Change way of thinking	

• Change way of coding	

• Anticipate future code evolution
Quick Example
Before
function resolveFirstName(person) {	
	
if (person.firstName)	
	
	
return person.firstName;	
	
else	
	
	
return "First name could not be found!";	
}	

!

function findAge(person) {	
	
return person.age;	
}	

!

function printOutName(person) {	
	
	
	
if (cookie === "senior") {	
	
	
findAge() + 20;	
	
	
resolveAddress();	
	
}	
	
	
	
return person.lastName || "No last name was found on record!";	
}
After
function errorMessage(descriptor) {	
	
return ({	
	
	
age : "Age could not be determined",	
	
	
firstName : "First name could not be found!",	
	
	
lastName : "No last name was found on record!"	
	
})[descriptor];	
}	

!

function resolveDescriptor(descriptor) {	
	
return typeof this[descriptor] !== "undefined"	
	
	
? this[descriptor]	
	
	
: errorMessage(descriptor);	
}	

!

function resolveSeniority() {	
	
if (cookie === "senior") {	
	
	
findAge() + 20;	
	
	
resolveAddress();	
	
}	
}
Paradigms
Overloading
• One function serves multiple purposes	

• Argument signature determines function	

• Must differ by arity or data types	

• Same function name	

• JavaScript can only simulate overloading
Example
function addMethod(object, name, fn){ // addMethod - By John Resig (MIT Licensed)	
var old = object[ name ];	
object[ name ] = function(){	
if ( fn.length == arguments.length )	
return fn.apply( this, arguments );	
else if ( typeof old == 'function' )	
return old.apply( this, arguments );	
};	
}	
function Users(){	
addMethod(this, "find", function(){	
// Find all users...	
});	
addMethod(this, "find", function(name){	
// Find a user by name	
});	
addMethod(this, "find", function(first, last){	
// Find a user by first and last name	
});	
}
Usage
var users = new Users();	

!

users.find(); // Finds all	

!

users.find("John"); // Finds users by name	

!

users.find("John", "Resig"); // Finds users by first and last name	

!

users.find("John", "E", "Resig"); // Does nothing
Events
• Usually we couple an event to a function	

• Sometimes many functions to one event	

• We know what happens on an event	

• We should not care what happens	

• Decouple handlers from events
Coupled Binding
Click
function () {

alert(‘hello world!’);

}
Decoupled Binding
Click

Load

Greet

function () {

alert(‘hello world!’);

}
Decoupled Binding
Greet

function
function

function () {

alert(‘hello world!’);

}
OOP
• Object oriented programming	

• Base classes are usually most abstract	

• Polymorphism	

• Duck typing	

• Composition
Procedural
joe();

function joe() {

sayHello();

}

jane();

function jane() {

sayHello();

}

function sayHello() {

alert(‘hello world!’);

}
Object Oriented
joe = new Person();

function Person() {

this.hi = sayHello;

}

jane = new Person();

joe.hi();

jane.hi();	


function sayHello() {

alert(‘hello world!’);

}
Example
function Person(name) {	
	
this.hi = sayHello;	
	
this.name = name;	
	
function sayHello() {	
	
	
console.log('hello world from ' + this.name);	
	
}	
}	

!

function init(names) {	
	
var people = [];	
	
for (var i = 0, count = names.length; i < count; i++) {	
	
	
people.push(new Person(names[i]));	
	
}	
	
return people;	
}	
function greet(people) {	
	
for (var i = 0, count = people.length; i < count; i++) {	
	
	
people[i].hi();	
	
}	
}	
greet(init(["Joe", "Jane"]));
Example
var Rifle = function () {	
	
this.reload = function () {};	
this.fire = function () { /* ... */ };	
},	

!

Cannon = function () {	
this.reload = function () {};	
this.fire = function () {};	
};	

!

var Soldier = function (gun) {	
this.currentGun = gun;	
this.inventory = {	
guns : [ gun ]	
};	
this.attack = function () { this.currentGun.fire(); };	
};	

!

var Tank = function (gun) {	
this.currentGun = gun;	
this.inventory = {	
guns : [ gun ]	
};	
this.attack = function () { this.currentGun.fire(); };	
};	

!

var soldier = new Soldier( new Rifle() ),	
tank
= new Tank( new Cannon() );
Example
var Rifle = function () {	
	
this.reload = function () {};	
this.fire = function () { /* ... */ };	
},	

!

Cannon = function () {	
this.reload = function () {};	
this.fire = function () {};	
};	

!

var Combatant = function (gun) {	
this.currentGun = gun;	
this.inventory = {	
guns : [ gun ]	
};	
this.attack = function () { this.currentGun.fire(); };	
};	

!

var soldier = new Combatant( new Rifle() ),	
tank
= new Combatant( new Cannon() );
MVC
• Abstraction engrained in architecture 	

• Separation of concerns (SoC)	

• Decouple model, view, controller	

• Each component replaceable	

• Any of these can be further abstracted
Traditional
JS
CSS
HTML
MVC
CSS
Data

HTML
JS
Example
function controller(model, view) {	
	
var items = “";	

!

	
	
	

for (var i = 0, count = model.items.length; i < count; i++) {	
	
items += view.item.replace("{{item}}", model.items[i]);	
}	

	
}	

return view.list.replace("{{items}}", items);	

!
!

var view = {	
	
item : "<li>{{item}}</li>",	
	
list : "<ul>{{items}}</ul>"	
};	

!

var model = {	
	
items : [1, 2, 3]	
};	

!

console.log(controller(model, view));
RWD / AWD
• Responsive responds to screen widths	

• Adaptive adapts to devices	

• Use mobile-first approach in all code	

• Segment code to accommodate growth	

• Use lazy loaders and module patterns
Coding
Thought Process
• Do not care for specifics	

• Do not care who calls what	

• Assume anyone can call anything	

• Assume anything can contain anything	

• Think interfaces not internals
APIs
• Make them intuitive	

• Do not rely on documentation	

• Provide switches for easy customization	

• Prioritize flexibility and agility of code	

• Design functions to handle one thing
Nomenclature
• Generalize identifiers	

• Don’t over-generalize, stay within context	

• Reverse name groupings	

• Group related variables in objects
Before
function buildPage()	
{	
	 var facebookIcon = "http://www.facebook.com/icon.png";	
	 	
	 while (someConditionIsTrue()){	
	 	
doSomeWork();	
	 }	
	 	
	
var i = resolveTwitterIcon();	
}	

!

var PinterestSmallLogo = pinterest();	

!

buildPage();
Improving
function buildPage()	
{	
	 var iconFacebook = "http://www.facebook.com/icon.png";	
	 	
	 while (someConditionIsTrue()){	
	 	
doSomeWork();	
	 }	
	 	
	
var iconTwitter = resolveTwitterIcon();	
}	

!

var iconPinterest = pinterest();	

!

buildPage();
After
function buildPage(icons)	
{	
	 icons.facebook = "http://www.facebook.com/icon.png";	
	 	
	 while (someConditionIsTrue()){	
	 	
doSomeWork();	
	 }	
	 	
	
icons.twitter = resolveTwitterIcon();	
}	

!

var
	
	
	
};	

!

icons = {	
facebook : "",	
pinterest : pinterest(),	
twitter : ""	

buildPage(icons);
Habit Forming
• Adhere to strict coding style	

• Remove comments	

• Progressively generalize identifiers	

• Identify similar patterns to normalize	

• Code in anticipation for change
Generalize
• This will do something	

• When something happens	

• It will take some parameters	

• Parameters will map to some object	

• The outcome will be specific to context
Example
function initModules()	
{	
	 for (module in app.modules) {	
	 	
if (app.modules[module].init && app.modules[module].checked()) {	
	 	
	
if (app.modules[module].init.call(this, arguments)) {	
	 	
	
	
initialized++;	
	 	
	
}	
	 	
}	
	 }	
}	
function initModules()	
{	
	 var module;	
	 for (moduleName in app.modules) {	
	 	
module = app.modules[moduleName];	
	 	
if (module.init && module.checked()) {	
	 	
	
if (module.init.call(this, arguments)) {	
	 	
	
	
initialized++;	
	 	
	
}	
	 	
}	
	 }	
}
Considerations
• Balance performance	

• Balance maintainability	

• Strive for quality	

• Balance code base size	

• Balance complexity
Exercise
0
1

2

3

4

5

6

7

8

9

+

0

*

Update on button click

Gray background

White border on click
Connect
• Thank you for your time	

• Connect with me on LinkedIn	

• Join the Hardcore JavaScript community	

• Read my blog	

• Contact me via e-mail

More Related Content

What's hot

jQuery Loves Developers - Oredev 2009
jQuery Loves Developers - Oredev 2009jQuery Loves Developers - Oredev 2009
jQuery Loves Developers - Oredev 2009Remy Sharp
 
Javascript Module Patterns
Javascript Module PatternsJavascript Module Patterns
Javascript Module PatternsNicholas Jansma
 
Proxies are Awesome!
Proxies are Awesome!Proxies are Awesome!
Proxies are Awesome!Brendan Eich
 
Art of Javascript
Art of JavascriptArt of Javascript
Art of JavascriptTarek Yehia
 
Modernizes your objective C - Oliviero
Modernizes your objective C - OlivieroModernizes your objective C - Oliviero
Modernizes your objective C - OlivieroCodemotion
 
Hey, I just met AngularJS, and this is crazy, so here’s my JavaScript, let’s ...
Hey, I just met AngularJS, and this is crazy, so here’s my JavaScript, let’s ...Hey, I just met AngularJS, and this is crazy, so here’s my JavaScript, let’s ...
Hey, I just met AngularJS, and this is crazy, so here’s my JavaScript, let’s ...Alessandro Nadalin
 
Building a Testable Data Access Layer
Building a Testable Data Access LayerBuilding a Testable Data Access Layer
Building a Testable Data Access LayerTodd Anglin
 
Developing iOS REST Applications
Developing iOS REST ApplicationsDeveloping iOS REST Applications
Developing iOS REST Applicationslmrei
 
Unobtrusive javascript with jQuery
Unobtrusive javascript with jQueryUnobtrusive javascript with jQuery
Unobtrusive javascript with jQueryAngel Ruiz
 
Scalable JavaScript Design Patterns
Scalable JavaScript Design PatternsScalable JavaScript Design Patterns
Scalable JavaScript Design PatternsAddy Osmani
 
jQuery Features to Avoid
jQuery Features to AvoidjQuery Features to Avoid
jQuery Features to Avoiddmethvin
 
Stack Overflow Austin - jQuery for Developers
Stack Overflow Austin - jQuery for DevelopersStack Overflow Austin - jQuery for Developers
Stack Overflow Austin - jQuery for DevelopersJonathan Sharp
 
Effecient javascript
Effecient javascriptEffecient javascript
Effecient javascriptmpnkhan
 
JS Level Up: Prototypes
JS Level Up: PrototypesJS Level Up: Prototypes
JS Level Up: PrototypesVernon Kesner
 
SharePoint and jQuery Essentials
SharePoint and jQuery EssentialsSharePoint and jQuery Essentials
SharePoint and jQuery EssentialsMark Rackley
 
Unit and functional testing with Siesta
Unit and functional testing with SiestaUnit and functional testing with Siesta
Unit and functional testing with SiestaGrgur Grisogono
 

What's hot (20)

Advanced Django
Advanced DjangoAdvanced Django
Advanced Django
 
ORMs in Golang
ORMs in GolangORMs in Golang
ORMs in Golang
 
jQuery Loves Developers - Oredev 2009
jQuery Loves Developers - Oredev 2009jQuery Loves Developers - Oredev 2009
jQuery Loves Developers - Oredev 2009
 
Javascript Module Patterns
Javascript Module PatternsJavascript Module Patterns
Javascript Module Patterns
 
Proxies are Awesome!
Proxies are Awesome!Proxies are Awesome!
Proxies are Awesome!
 
jQuery Essentials
jQuery EssentialsjQuery Essentials
jQuery Essentials
 
Art of Javascript
Art of JavascriptArt of Javascript
Art of Javascript
 
Modernizes your objective C - Oliviero
Modernizes your objective C - OlivieroModernizes your objective C - Oliviero
Modernizes your objective C - Oliviero
 
Hey, I just met AngularJS, and this is crazy, so here’s my JavaScript, let’s ...
Hey, I just met AngularJS, and this is crazy, so here’s my JavaScript, let’s ...Hey, I just met AngularJS, and this is crazy, so here’s my JavaScript, let’s ...
Hey, I just met AngularJS, and this is crazy, so here’s my JavaScript, let’s ...
 
Building a Testable Data Access Layer
Building a Testable Data Access LayerBuilding a Testable Data Access Layer
Building a Testable Data Access Layer
 
Developing iOS REST Applications
Developing iOS REST ApplicationsDeveloping iOS REST Applications
Developing iOS REST Applications
 
Unobtrusive javascript with jQuery
Unobtrusive javascript with jQueryUnobtrusive javascript with jQuery
Unobtrusive javascript with jQuery
 
Scalable JavaScript Design Patterns
Scalable JavaScript Design PatternsScalable JavaScript Design Patterns
Scalable JavaScript Design Patterns
 
jQuery Features to Avoid
jQuery Features to AvoidjQuery Features to Avoid
jQuery Features to Avoid
 
Stack Overflow Austin - jQuery for Developers
Stack Overflow Austin - jQuery for DevelopersStack Overflow Austin - jQuery for Developers
Stack Overflow Austin - jQuery for Developers
 
Effecient javascript
Effecient javascriptEffecient javascript
Effecient javascript
 
JS Level Up: Prototypes
JS Level Up: PrototypesJS Level Up: Prototypes
JS Level Up: Prototypes
 
SharePoint and jQuery Essentials
SharePoint and jQuery EssentialsSharePoint and jQuery Essentials
SharePoint and jQuery Essentials
 
Unit and functional testing with Siesta
Unit and functional testing with SiestaUnit and functional testing with Siesta
Unit and functional testing with Siesta
 
jQuery in 15 minutes
jQuery in 15 minutesjQuery in 15 minutes
jQuery in 15 minutes
 

Similar to JavaScript Abstraction

Maintainable JavaScript 2012
Maintainable JavaScript 2012Maintainable JavaScript 2012
Maintainable JavaScript 2012Nicholas Zakas
 
Maintainable JavaScript 2011
Maintainable JavaScript 2011Maintainable JavaScript 2011
Maintainable JavaScript 2011Nicholas Zakas
 
Twins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingTwins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingRichardWarburton
 
Awesomeness of JavaScript…almost
Awesomeness of JavaScript…almostAwesomeness of JavaScript…almost
Awesomeness of JavaScript…almostQuinton Sheppard
 
Java script object model
Java script object modelJava script object model
Java script object modelJames Hsieh
 
TWINS: OOP and FP - Warburton
TWINS: OOP and FP - WarburtonTWINS: OOP and FP - Warburton
TWINS: OOP and FP - WarburtonCodemotion
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsJeff Durta
 
Javascript Frameworks for Joomla
Javascript Frameworks for JoomlaJavascript Frameworks for Joomla
Javascript Frameworks for JoomlaLuke Summerfield
 
Three Simple Chords of Alternative PageObjects and Hardcore of LoadableCompon...
Three Simple Chords of Alternative PageObjects and Hardcore of LoadableCompon...Three Simple Chords of Alternative PageObjects and Hardcore of LoadableCompon...
Three Simple Chords of Alternative PageObjects and Hardcore of LoadableCompon...Iakiv Kramarenko
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5arajivmordani
 
Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Librariesjeresig
 

Similar to JavaScript Abstraction (20)

Maintainable JavaScript 2012
Maintainable JavaScript 2012Maintainable JavaScript 2012
Maintainable JavaScript 2012
 
JS Essence
JS EssenceJS Essence
JS Essence
 
Performance patterns
Performance patternsPerformance patterns
Performance patterns
 
"Javascript" por Tiago Rodrigues
"Javascript" por Tiago Rodrigues"Javascript" por Tiago Rodrigues
"Javascript" por Tiago Rodrigues
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
 
Maintainable JavaScript 2011
Maintainable JavaScript 2011Maintainable JavaScript 2011
Maintainable JavaScript 2011
 
Twins: OOP and FP
Twins: OOP and FPTwins: OOP and FP
Twins: OOP and FP
 
JavaScript for real men
JavaScript for real menJavaScript for real men
JavaScript for real men
 
Twins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingTwins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional Programming
 
Awesomeness of JavaScript…almost
Awesomeness of JavaScript…almostAwesomeness of JavaScript…almost
Awesomeness of JavaScript…almost
 
Java script object model
Java script object modelJava script object model
Java script object model
 
TWINS: OOP and FP - Warburton
TWINS: OOP and FP - WarburtonTWINS: OOP and FP - Warburton
TWINS: OOP and FP - Warburton
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applications
 
Javascript Frameworks for Joomla
Javascript Frameworks for JoomlaJavascript Frameworks for Joomla
Javascript Frameworks for Joomla
 
Three Simple Chords of Alternative PageObjects and Hardcore of LoadableCompon...
Three Simple Chords of Alternative PageObjects and Hardcore of LoadableCompon...Three Simple Chords of Alternative PageObjects and Hardcore of LoadableCompon...
Three Simple Chords of Alternative PageObjects and Hardcore of LoadableCompon...
 
Lecture 6: Client Side Programming 2
Lecture 6: Client Side Programming 2Lecture 6: Client Side Programming 2
Lecture 6: Client Side Programming 2
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5a
 
Gwt.create
Gwt.createGwt.create
Gwt.create
 
Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Libraries
 
JavaScript
JavaScriptJavaScript
JavaScript
 

Recently uploaded

Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
[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
 
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
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
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
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
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
 
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
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 

Recently uploaded (20)

Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
[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
 
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
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
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
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
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
 
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
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 

JavaScript Abstraction

  • 1. JavaScript Abstraction in Implementation ! by Milan Adamovsky http://milan.adamovsky.com ◆ http://www.hardcorejs.com
  • 2. Preface • Based on personal observations • Spanning over 15 companies • Small companies to mostly enterprise • Not based on comprehensive research • Full life cycle of web development
  • 4. Analyze <html> <head> <title> This is the title of the page </title> </head> <body> <p id="main_content"> This is my content </p> <ul> <li class="first"> One <li> Two <ol> <li class="first"> A </ol> <li> </ul> </body> </html>
  • 5. Analysis • A document • A tree of hierarchal nodes off of root node • Two children nodes off of root node • Second child node has two children nodes • Two children nodes are siblings
  • 6. Overview • Ultimate goal is to write less code • Increase reusability • Change way of thinking • Change way of coding • Anticipate future code evolution
  • 8. Before function resolveFirstName(person) { if (person.firstName) return person.firstName; else return "First name could not be found!"; } ! function findAge(person) { return person.age; } ! function printOutName(person) { if (cookie === "senior") { findAge() + 20; resolveAddress(); } return person.lastName || "No last name was found on record!"; }
  • 9. After function errorMessage(descriptor) { return ({ age : "Age could not be determined", firstName : "First name could not be found!", lastName : "No last name was found on record!" })[descriptor]; } ! function resolveDescriptor(descriptor) { return typeof this[descriptor] !== "undefined" ? this[descriptor] : errorMessage(descriptor); } ! function resolveSeniority() { if (cookie === "senior") { findAge() + 20; resolveAddress(); } }
  • 11. Overloading • One function serves multiple purposes • Argument signature determines function • Must differ by arity or data types • Same function name • JavaScript can only simulate overloading
  • 12. Example function addMethod(object, name, fn){ // addMethod - By John Resig (MIT Licensed) var old = object[ name ]; object[ name ] = function(){ if ( fn.length == arguments.length ) return fn.apply( this, arguments ); else if ( typeof old == 'function' ) return old.apply( this, arguments ); }; } function Users(){ addMethod(this, "find", function(){ // Find all users... }); addMethod(this, "find", function(name){ // Find a user by name }); addMethod(this, "find", function(first, last){ // Find a user by first and last name }); }
  • 13. Usage var users = new Users(); ! users.find(); // Finds all ! users.find("John"); // Finds users by name ! users.find("John", "Resig"); // Finds users by first and last name ! users.find("John", "E", "Resig"); // Does nothing
  • 14. Events • Usually we couple an event to a function • Sometimes many functions to one event • We know what happens on an event • We should not care what happens • Decouple handlers from events
  • 15. Coupled Binding Click function () {
 alert(‘hello world!’);
 }
  • 16. Decoupled Binding Click Load Greet function () {
 alert(‘hello world!’);
 }
  • 17. Decoupled Binding Greet function function function () {
 alert(‘hello world!’);
 }
  • 18. OOP • Object oriented programming • Base classes are usually most abstract • Polymorphism • Duck typing • Composition
  • 19. Procedural joe(); function joe() {
 sayHello();
 } jane(); function jane() {
 sayHello();
 } function sayHello() {
 alert(‘hello world!’);
 }
  • 20. Object Oriented joe = new Person(); function Person() {
 this.hi = sayHello;
 } jane = new Person(); joe.hi();
 jane.hi(); function sayHello() {
 alert(‘hello world!’);
 }
  • 21. Example function Person(name) { this.hi = sayHello; this.name = name; function sayHello() { console.log('hello world from ' + this.name); } } ! function init(names) { var people = []; for (var i = 0, count = names.length; i < count; i++) { people.push(new Person(names[i])); } return people; } function greet(people) { for (var i = 0, count = people.length; i < count; i++) { people[i].hi(); } } greet(init(["Joe", "Jane"]));
  • 22. Example var Rifle = function () { this.reload = function () {}; this.fire = function () { /* ... */ }; }, ! Cannon = function () { this.reload = function () {}; this.fire = function () {}; }; ! var Soldier = function (gun) { this.currentGun = gun; this.inventory = { guns : [ gun ] }; this.attack = function () { this.currentGun.fire(); }; }; ! var Tank = function (gun) { this.currentGun = gun; this.inventory = { guns : [ gun ] }; this.attack = function () { this.currentGun.fire(); }; }; ! var soldier = new Soldier( new Rifle() ), tank = new Tank( new Cannon() );
  • 23. Example var Rifle = function () { this.reload = function () {}; this.fire = function () { /* ... */ }; }, ! Cannon = function () { this.reload = function () {}; this.fire = function () {}; }; ! var Combatant = function (gun) { this.currentGun = gun; this.inventory = { guns : [ gun ] }; this.attack = function () { this.currentGun.fire(); }; }; ! var soldier = new Combatant( new Rifle() ), tank = new Combatant( new Cannon() );
  • 24. MVC • Abstraction engrained in architecture • Separation of concerns (SoC) • Decouple model, view, controller • Each component replaceable • Any of these can be further abstracted
  • 27. Example function controller(model, view) { var items = “"; ! for (var i = 0, count = model.items.length; i < count; i++) { items += view.item.replace("{{item}}", model.items[i]); } } return view.list.replace("{{items}}", items); ! ! var view = { item : "<li>{{item}}</li>", list : "<ul>{{items}}</ul>" }; ! var model = { items : [1, 2, 3] }; ! console.log(controller(model, view));
  • 28. RWD / AWD • Responsive responds to screen widths • Adaptive adapts to devices • Use mobile-first approach in all code • Segment code to accommodate growth • Use lazy loaders and module patterns
  • 30. Thought Process • Do not care for specifics • Do not care who calls what • Assume anyone can call anything • Assume anything can contain anything • Think interfaces not internals
  • 31. APIs • Make them intuitive • Do not rely on documentation • Provide switches for easy customization • Prioritize flexibility and agility of code • Design functions to handle one thing
  • 32. Nomenclature • Generalize identifiers • Don’t over-generalize, stay within context • Reverse name groupings • Group related variables in objects
  • 33. Before function buildPage() { var facebookIcon = "http://www.facebook.com/icon.png"; while (someConditionIsTrue()){ doSomeWork(); } var i = resolveTwitterIcon(); } ! var PinterestSmallLogo = pinterest(); ! buildPage();
  • 34. Improving function buildPage() { var iconFacebook = "http://www.facebook.com/icon.png"; while (someConditionIsTrue()){ doSomeWork(); } var iconTwitter = resolveTwitterIcon(); } ! var iconPinterest = pinterest(); ! buildPage();
  • 35. After function buildPage(icons) { icons.facebook = "http://www.facebook.com/icon.png"; while (someConditionIsTrue()){ doSomeWork(); } icons.twitter = resolveTwitterIcon(); } ! var }; ! icons = { facebook : "", pinterest : pinterest(), twitter : "" buildPage(icons);
  • 36. Habit Forming • Adhere to strict coding style • Remove comments • Progressively generalize identifiers • Identify similar patterns to normalize • Code in anticipation for change
  • 37. Generalize • This will do something • When something happens • It will take some parameters • Parameters will map to some object • The outcome will be specific to context
  • 38. Example function initModules() { for (module in app.modules) { if (app.modules[module].init && app.modules[module].checked()) { if (app.modules[module].init.call(this, arguments)) { initialized++; } } } } function initModules() { var module; for (moduleName in app.modules) { module = app.modules[moduleName]; if (module.init && module.checked()) { if (module.init.call(this, arguments)) { initialized++; } } } }
  • 39. Considerations • Balance performance • Balance maintainability • Strive for quality • Balance code base size • Balance complexity
  • 40. Exercise 0 1 2 3 4 5 6 7 8 9 + 0 * Update on button click Gray background White border on click
  • 41. Connect • Thank you for your time • Connect with me on LinkedIn • Join the Hardcore JavaScript community • Read my blog • Contact me via e-mail