SlideShare une entreprise Scribd logo
1  sur  49
Télécharger pour lire hors ligne
Defensive Programming
in Javascript & node.js
Wednesday, May 29, 13
INTRODUCTION
Ruben Tan Long Zheng 陈龙正
VP of Engineering, OnApp CDN KL
Lead Engineer, 40 Square Sdn Bhd
Javascript > 5 years
@roguejs
Organizer of Nodehack KL
Wednesday, May 29, 13
OVERVIEW
Dependency Awareness
Javascript Mastery
Methodology Improvements
Wednesday, May 29, 13
SEASON 1
DEPENDENCY
AWARENESS
Wednesday, May 29, 13
Internal dependencies
Libraries
require(), include()
External dependencies
Services, files, databases, etc
socket.connect(), db.open()
DEPENDENCY TYPES
Wednesday, May 29, 13
NEVER ASSUME!
Never assume a dependency is reliable!
var db = require(‘database’);
db.open();
db.write(‘foo bar’, function (err, data) {
// ... do something ...
});
Wednesday, May 29, 13
NEVER ASSUME!
var db = require(‘database’);
db.open();
db.write(‘foo bar’, function (err, data) {
// ... do something ...
});
What if this failed?
will write() throw an error? will open() throw
an exception?
Wednesday, May 29, 13
NEVER ASSUME!
var db = require(‘database’);
db.open(function (err) {
db.write(‘mr-big’, bigData, function (err, data) {
// ... unrelated logic
db.close();
});
db.read(‘foo2’, function (err, data) {
// ... some work done
});
});
Accidents happen...
Wednesday, May 29, 13
NEVER ASSUME!
var db = require(‘database’);
db.open(function (err) {
db.write(‘mr-big’, bigData, function (err, data) {
// ... unrelated logic
db.close();
});
db.read(‘foo2’, function (err, data) {
// ... some work done
});
});
close() might affect read()
Wednesday, May 29, 13
A MORE COMPLEX EXAMPLE...
Wednesday, May 29, 13
VIDEO STREAMING SERVICE
Video
Streamer
Origin
Stats
Logger
VOD
Client
User
Accounting
UploadLive
Client
User
Stream
Stream
LogReport
Render
Render
Wednesday, May 29, 13
VIDEO STREAMING SERVICE
Video
Streamer
Origin
Stats
Logger
VOD
Client
User
Accounting
UploadLive
Client
User
Stream
Stream
LogReport
Render
Render
1
2
3
4
5
6
7
8
9
10
11
Wednesday, May 29, 13
DEPENDENCY AWARENESS
What can fail, WILL FAIL!
Never assume a dependency is reliable!
Contingency plans - failover, redundancy, fail-fast, etc
Pro-active monitoring
Load test, stress test, chaos monkey, etc
Remember, what can fail, WILL FAIL!
Wednesday, May 29, 13
SEASON 2
JAVASCRIPT MASTERY
Wednesday, May 29, 13
JAVASCRIPT MASTERY
Code Execution Order
Sanitization & Validation
Scope
Control Flow
Wednesday, May 29, 13
I KNOW CODE-FU!
Wednesday, May 29, 13
EXECUTION ORDER
var mq = require(‘mq’);
mq.conn(...);
mq.on(‘ready’, function () {
mq.send(‘batman’);
mq.on(‘message’, function (msg) {
console.log(msg);
mq.close();
});
});
mq is never closed!
send() executes before on()
Wednesday, May 29, 13
DOIN’ IT RIGHT!
var mq = require(‘mq’);
mq.conn(...);
mq.on(‘ready’, function () {
mq.on(‘message’, function (msg) {
console.log(msg);
mq.close();
});
mq.send(‘batman’);
});
Swap places
Wednesday, May 29, 13
SANITIZATION & VALIDATION
function foodForKittens(num) {
return num * 10;
}
foodForKittens();
num is not validated, is undefined
this will fail!
Wednesday, May 29, 13
TOO SIMPLE?
Wednesday, May 29, 13
SANITIZATION & VALIDATION
var db = require(‘database’);
var conn = db.open(...);
function writeToDb(conn, cb) {
conn.write(bigData, function (err, res) {
if (err) {
cb(err);
return;
}
cb(null, res);
});
});
writeToDb(conn, ghostCallback);
Wednesday, May 29, 13
Wednesday, May 29, 13
var db = require(‘database’);
var conn = db.open(...);
function writeToDb(conn, cb) {
conn.write(bigData, function (err, res) {
if (err) {
cb(err);
return;
}
cb(null, res);
});
});
writeToDb(conn, ghostCallback);
what if open() returned undefined?
this will throw an exception!
Wednesday, May 29, 13
var db = require(‘database’);
var conn = db.open(...);
function writeToDb(conn, cb) {
conn.write(bigData, function (err, res) {
if (err) {
cb(err);
return;
}
cb(null, res);
});
});
writeToDb(conn, ghostCallback);
What if ghostCallback is undefined?
These will fail too!
Wednesday, May 29, 13
DOIN’ IT RIGHT!
var db = require(‘database’);
var conn = db.open(...);
function writeToDb(conn, cb) {
if (typeof conn !== ‘object’) {
// ... handle error ...
}
if (typeof cb !== ‘function’) {
// ... handle error ...
}
conn.write(bigData, function (err, res) {
if (err) {
cb(err);
return;
}
cb(null, res);
});
});
writeToDb(conn, ghostCallback);
Validate your input,
especially when they
involve functions or
methods that you need to
invoke in your code.
These are not the time to
fail-fast!
Wednesday, May 29, 13
DON’T GO OVERBOARD...
Validate only necessary parameters
Method invocations (anObject.method())
Function invocations (aFunction())
Have a proper error/exception handling policy
Validate for correctness, not existence
Correctness: typeof a === ‘object’
Existence: a !== undefined
Wednesday, May 29, 13
SCOPE AWARENESS
Plagues most callback-based code
Bad practice leads to costly debugging waste
New JS programmers not aware of scoping
JS scoping is a simple but weird thing (to non-JS
programmers)
Wednesday, May 29, 13
SCOPE!!!
var a = ‘outside’;
if (true) {
var a = ‘inside’;
console.log(a);
}
console.log(a);
What is the output?
> node test.js
inside
inside
Wednesday, May 29, 13
SCOPE!!!
Non-JS programmers:
a inside the if block is “inside”
a outside the if block is “outside”
JS programmers:
they are both “inside”
JS scope by function
Wednesday, May 29, 13
SCOPE CHAINS!!!
var avar = 1;
(function outer1() {
var avar = 2;
(function inner1() {
var avar = 3;
console.log(avar); // outputs 3
})();
(function inner2() {
console.log(avar); // outputs 2
})();
})();
(function outer2() {
(function inner3() {
console.log(avar); // outputs 1
})();
})();
inner1()
local - found!
inner2()
local - nope
outer1() - found!
inner3()
local - nope
outer2() - nope
global - found!
Wednesday, May 29, 13
HOISTING VARIABLES
function () {
for (var i = 0; i < 10; i++) {
for (var j = 0; j < 10; j++) {
// ... do something
}
}
}
function () {
var i, j; // now the scope is clear for i & j
for (i = 0; i < 10; i++) {
for (j = 0; j < 10; j++) {
// ... do something
}
}
}
Below is far clearer what individual variable scopes are:
Wednesday, May 29, 13
CONTROL FLOW
Node.js’ async nature makes it unintuitive to predict
control flow
I <3 async (github.com/caolan/async)
Control flow is ugly. Welcome to Javascript.
Async will save your life. Use it.
Wednesday, May 29, 13
CONTROL FLOW
var fs;
fs = require(‘fs’);
fs.readFile(‘./myfile.txt’, function (err, data) {
if (err) {
console.log(err);
return;
}
fs.writeFile(‘./myfile2.txt’, data, function (err) {
if (err) {
console.log(err);
return;
}
// ... do stuff ...
});
})
Wednesday, May 29, 13
CONTROL FLOW
Callback hell!
Step 1
Step 2
Step 3
Step 4
Step 5
Wednesday, May 29, 13
mod.step1(function () {
mod.step2(function () {
mod.step3(function () {
mod.step4(function () {
mod.step5(function () {
// ... too many levels ...
});
});
}
});
});
Wednesday, May 29, 13
CONTROL FLOW
var async, fs;
async = require(‘async’);
fs = require(‘fs’);
async.waterfall([
function step1(callback) {
fs.readFile(‘./myfile.txt’, callback);
},
function step2(data, callback) {
fs.writeFile(‘./myfile2.txt’, data, callback);
}
], function (err) {
// ... execute something in the end ...
});
Wednesday, May 29, 13
SEASON 3
METHODOLOGY
IMPROVEMENTS
Wednesday, May 29, 13
GOLDEN RULES
Golden Rules of Defensive Programming
Proper error handling policy
Intelligent logging
Design for failure
Wednesday, May 29, 13
ERROR HANDLING
Never, ever HIDE errors
> node app.js 2>&1 /dev/null
ob.callback(function (err, data) {
if (err) {}
console.log(data);
});
socket.on(‘error’, function () {});
Wednesday, May 29, 13
ERROR HANDLING
I WILL FIND YOU
AND I WILL CRASH YOU
Wednesday, May 29, 13
ERROR HANDLING
Standardize error handling in the app
Log to error DB
Output to error file
Output error to a stream
Use a logging library
Ask a leprechaun to manage it
etc
Wednesday, May 29, 13
LOGGING
How do you feel if your “log” looks like this?
> tail -f error.log
[12:01:55] ERROR - General error detected
[12:01:56] ERROR - General error detected
[12:01:57] ERROR - General error detected
[12:01:58] ERROR - General error detected
[12:01:59] ERROR - General error detected
[12:02:00] ERROR - General error detected
[12:02:01] ERROR - General error detected
Wednesday, May 29, 13
LOGGING
Wednesday, May 29, 13
LOGGING
Logs are the first place you go to find out what
happened
Standardize a log location for each app
Make logs easy to access for developers
Wednesday, May 29, 13
DESIGN FOR FAILURE
Common steps to designing software:
1 - what should it do?
2 - how do I do it?
3 - how do I deploy?
4 - done
Wednesday, May 29, 13
DESIGN FOR FAILURE
Proper steps in defensive programming:
1 - what should it do?
2 - how many ways can it fail?
3 - how do I know when it fails?
4 - how do I prevent it from failing?
5 - write code accordingly
Wednesday, May 29, 13
DESIGN FOR FAILURE
Nothing is reliable
TCP can fail
Network can go down
Servers can run out of memory
Cows might fly through the sky crashing into your
datacenter and flooding the server rooms with milk
and destroying everything
Wednesday, May 29, 13
DESIGN FOR FAILURE
Designing for failure mindset & methodologies:
Identify SPOF (single point of failures)
Redundancy, failover, monitoring
Fail-fast, start-fast
Persist important data
Reliability & Consistency > Speed
Code is liability
Wednesday, May 29, 13
~ The End ~
Wednesday, May 29, 13

Contenu connexe

Tendances

PostgreSQL Tutorial for Beginners | Edureka
PostgreSQL Tutorial for Beginners | EdurekaPostgreSQL Tutorial for Beginners | Edureka
PostgreSQL Tutorial for Beginners | EdurekaEdureka!
 
Oracle Database Overview
Oracle Database OverviewOracle Database Overview
Oracle Database Overviewhonglee71
 
Exploring Oracle Database Performance Tuning Best Practices for DBAs and Deve...
Exploring Oracle Database Performance Tuning Best Practices for DBAs and Deve...Exploring Oracle Database Performance Tuning Best Practices for DBAs and Deve...
Exploring Oracle Database Performance Tuning Best Practices for DBAs and Deve...Aaron Shilo
 
Oracle Database Performance Tuning Basics
Oracle Database Performance Tuning BasicsOracle Database Performance Tuning Basics
Oracle Database Performance Tuning Basicsnitin anjankar
 
SQL vs NoSQL | MySQL vs MongoDB Tutorial | Edureka
SQL vs NoSQL | MySQL vs MongoDB Tutorial | EdurekaSQL vs NoSQL | MySQL vs MongoDB Tutorial | Edureka
SQL vs NoSQL | MySQL vs MongoDB Tutorial | EdurekaEdureka!
 
10 Problems with your RMAN backup script - whitepaper
10 Problems with your RMAN backup script - whitepaper10 Problems with your RMAN backup script - whitepaper
10 Problems with your RMAN backup script - whitepaperYury Velikanov
 
Optimizing Alert Monitoring with Oracle Enterprise Manager
Optimizing Alert Monitoring with Oracle Enterprise ManagerOptimizing Alert Monitoring with Oracle Enterprise Manager
Optimizing Alert Monitoring with Oracle Enterprise ManagerDatavail
 
Performance Tuning Oracle Weblogic Server 12c
Performance Tuning Oracle Weblogic Server 12cPerformance Tuning Oracle Weblogic Server 12c
Performance Tuning Oracle Weblogic Server 12cAjith Narayanan
 
EM12c: Capacity Planning with OEM Metrics
EM12c: Capacity Planning with OEM MetricsEM12c: Capacity Planning with OEM Metrics
EM12c: Capacity Planning with OEM MetricsMaaz Anjum
 
On to code review lessons learned at microsoft
On to code review lessons learned at microsoftOn to code review lessons learned at microsoft
On to code review lessons learned at microsoftMichaela Greiler
 
Overview of query evaluation
Overview of query evaluationOverview of query evaluation
Overview of query evaluationavniS
 
Your tuning arsenal: AWR, ADDM, ASH, Metrics and Advisors
Your tuning arsenal: AWR, ADDM, ASH, Metrics and AdvisorsYour tuning arsenal: AWR, ADDM, ASH, Metrics and Advisors
Your tuning arsenal: AWR, ADDM, ASH, Metrics and AdvisorsJohn Kanagaraj
 

Tendances (20)

Defensive Apex Programming
Defensive Apex ProgrammingDefensive Apex Programming
Defensive Apex Programming
 
PostgreSQL Tutorial for Beginners | Edureka
PostgreSQL Tutorial for Beginners | EdurekaPostgreSQL Tutorial for Beginners | Edureka
PostgreSQL Tutorial for Beginners | Edureka
 
Oracle Database Overview
Oracle Database OverviewOracle Database Overview
Oracle Database Overview
 
Exploring Oracle Database Performance Tuning Best Practices for DBAs and Deve...
Exploring Oracle Database Performance Tuning Best Practices for DBAs and Deve...Exploring Oracle Database Performance Tuning Best Practices for DBAs and Deve...
Exploring Oracle Database Performance Tuning Best Practices for DBAs and Deve...
 
Database Testing
Database TestingDatabase Testing
Database Testing
 
Software Testing
Software TestingSoftware Testing
Software Testing
 
Oracle Database Performance Tuning Basics
Oracle Database Performance Tuning BasicsOracle Database Performance Tuning Basics
Oracle Database Performance Tuning Basics
 
SQL vs NoSQL | MySQL vs MongoDB Tutorial | Edureka
SQL vs NoSQL | MySQL vs MongoDB Tutorial | EdurekaSQL vs NoSQL | MySQL vs MongoDB Tutorial | Edureka
SQL vs NoSQL | MySQL vs MongoDB Tutorial | Edureka
 
10 Problems with your RMAN backup script - whitepaper
10 Problems with your RMAN backup script - whitepaper10 Problems with your RMAN backup script - whitepaper
10 Problems with your RMAN backup script - whitepaper
 
Optimizing Alert Monitoring with Oracle Enterprise Manager
Optimizing Alert Monitoring with Oracle Enterprise ManagerOptimizing Alert Monitoring with Oracle Enterprise Manager
Optimizing Alert Monitoring with Oracle Enterprise Manager
 
Performance tuning in sql server
Performance tuning in sql serverPerformance tuning in sql server
Performance tuning in sql server
 
Performance Tuning Oracle Weblogic Server 12c
Performance Tuning Oracle Weblogic Server 12cPerformance Tuning Oracle Weblogic Server 12c
Performance Tuning Oracle Weblogic Server 12c
 
EM12c: Capacity Planning with OEM Metrics
EM12c: Capacity Planning with OEM MetricsEM12c: Capacity Planning with OEM Metrics
EM12c: Capacity Planning with OEM Metrics
 
On to code review lessons learned at microsoft
On to code review lessons learned at microsoftOn to code review lessons learned at microsoft
On to code review lessons learned at microsoft
 
Unit 2
Unit 2Unit 2
Unit 2
 
Oracle 12c Architecture
Oracle 12c ArchitectureOracle 12c Architecture
Oracle 12c Architecture
 
Requirements Engineering
Requirements EngineeringRequirements Engineering
Requirements Engineering
 
Overview of query evaluation
Overview of query evaluationOverview of query evaluation
Overview of query evaluation
 
Your tuning arsenal: AWR, ADDM, ASH, Metrics and Advisors
Your tuning arsenal: AWR, ADDM, ASH, Metrics and AdvisorsYour tuning arsenal: AWR, ADDM, ASH, Metrics and Advisors
Your tuning arsenal: AWR, ADDM, ASH, Metrics and Advisors
 
One PDB to go, please!
One PDB to go, please!One PDB to go, please!
One PDB to go, please!
 

En vedette

Blood Coagulation, its Mechanism Disorders and its role in Human Life
Blood Coagulation, its Mechanism Disorders and its role in Human LifeBlood Coagulation, its Mechanism Disorders and its role in Human Life
Blood Coagulation, its Mechanism Disorders and its role in Human LifeFiverr (Fiverr.com)
 
The Blood Cell, Immunity and blood coagulation
The Blood Cell, Immunity and blood coagulationThe Blood Cell, Immunity and blood coagulation
The Blood Cell, Immunity and blood coagulationnilofer24
 
Hematology: Blood coagulation
Hematology: Blood coagulationHematology: Blood coagulation
Hematology: Blood coagulationProtegeNithi
 
Mechanism of blood coagulation /certified fixed orthodontic courses by Indian...
Mechanism of blood coagulation /certified fixed orthodontic courses by Indian...Mechanism of blood coagulation /certified fixed orthodontic courses by Indian...
Mechanism of blood coagulation /certified fixed orthodontic courses by Indian...Indian dental academy
 
Coagulation cascade
Coagulation cascadeCoagulation cascade
Coagulation cascadeniraj phoju
 
Hemostasis and blood coagulation general pathology
Hemostasis and blood  coagulation general pathologyHemostasis and blood  coagulation general pathology
Hemostasis and blood coagulation general pathologySiganga Siganga
 
AngularJS Security: defend your Single Page Application
AngularJS Security: defend your Single Page Application AngularJS Security: defend your Single Page Application
AngularJS Security: defend your Single Page Application Carlo Bonamico
 
Blood coagulation
Blood coagulationBlood coagulation
Blood coagulationGunJee Gj
 

En vedette (17)

Blood and its importance
Blood and its importanceBlood and its importance
Blood and its importance
 
Protection
ProtectionProtection
Protection
 
Blood Coagulation, its Mechanism Disorders and its role in Human Life
Blood Coagulation, its Mechanism Disorders and its role in Human LifeBlood Coagulation, its Mechanism Disorders and its role in Human Life
Blood Coagulation, its Mechanism Disorders and its role in Human Life
 
The Blood Cell, Immunity and blood coagulation
The Blood Cell, Immunity and blood coagulationThe Blood Cell, Immunity and blood coagulation
The Blood Cell, Immunity and blood coagulation
 
Hematology: Blood coagulation
Hematology: Blood coagulationHematology: Blood coagulation
Hematology: Blood coagulation
 
Mechanism of blood coagulation /certified fixed orthodontic courses by Indian...
Mechanism of blood coagulation /certified fixed orthodontic courses by Indian...Mechanism of blood coagulation /certified fixed orthodontic courses by Indian...
Mechanism of blood coagulation /certified fixed orthodontic courses by Indian...
 
Coagulation cascade
Coagulation cascadeCoagulation cascade
Coagulation cascade
 
Hemostasis and blood coagulation general pathology
Hemostasis and blood  coagulation general pathologyHemostasis and blood  coagulation general pathology
Hemostasis and blood coagulation general pathology
 
Node.js security
Node.js securityNode.js security
Node.js security
 
blood clotting
blood clottingblood clotting
blood clotting
 
Coagulation
CoagulationCoagulation
Coagulation
 
Blood coagulation
Blood coagulationBlood coagulation
Blood coagulation
 
Blood Physiology - Ppt
Blood Physiology - PptBlood Physiology - Ppt
Blood Physiology - Ppt
 
AngularJS Security: defend your Single Page Application
AngularJS Security: defend your Single Page Application AngularJS Security: defend your Single Page Application
AngularJS Security: defend your Single Page Application
 
Blood physiology
Blood physiologyBlood physiology
Blood physiology
 
Blood coagulation
Blood coagulationBlood coagulation
Blood coagulation
 
Blood and blood transfusions
Blood and blood transfusionsBlood and blood transfusions
Blood and blood transfusions
 

Similaire à Defensive programming in Javascript and Node.js

Your Library Sucks, and why you should use it.
Your Library Sucks, and why you should use it.Your Library Sucks, and why you should use it.
Your Library Sucks, and why you should use it.Peter Higgins
 
5 Tips for Better JavaScript
5 Tips for Better JavaScript5 Tips for Better JavaScript
5 Tips for Better JavaScriptTodd Anglin
 
Operationalizing Clojure Confidently
Operationalizing Clojure ConfidentlyOperationalizing Clojure Confidently
Operationalizing Clojure ConfidentlyPrasanna Gautam
 
2013-06-15 - Software Craftsmanship mit JavaScript
2013-06-15 - Software Craftsmanship mit JavaScript2013-06-15 - Software Craftsmanship mit JavaScript
2013-06-15 - Software Craftsmanship mit JavaScriptJohannes Hoppe
 
2013-06-24 - Software Craftsmanship with JavaScript
2013-06-24 - Software Craftsmanship with JavaScript2013-06-24 - Software Craftsmanship with JavaScript
2013-06-24 - Software Craftsmanship with JavaScriptJohannes Hoppe
 
2 Years of Real World FP at REA
2 Years of Real World FP at REA2 Years of Real World FP at REA
2 Years of Real World FP at REAkenbot
 
Beautiful PHP CLI Scripts
Beautiful PHP CLI ScriptsBeautiful PHP CLI Scripts
Beautiful PHP CLI ScriptsJesse Donat
 
Subtle Asynchrony by Jeff Hammond
Subtle Asynchrony by Jeff HammondSubtle Asynchrony by Jeff Hammond
Subtle Asynchrony by Jeff HammondPatrick Diehl
 
Kamil witecki asynchronous, yet readable, code
Kamil witecki asynchronous, yet readable, codeKamil witecki asynchronous, yet readable, code
Kamil witecki asynchronous, yet readable, codeKamil Witecki
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing UpDavid Padbury
 
Playing With Fire - An Introduction to Node.js
Playing With Fire - An Introduction to Node.jsPlaying With Fire - An Introduction to Node.js
Playing With Fire - An Introduction to Node.jsMike Hagedorn
 
Building resilient services in go
Building resilient services in goBuilding resilient services in go
Building resilient services in goJaehue Jang
 
PHP CLI: A Cinderella Story
PHP CLI: A Cinderella StoryPHP CLI: A Cinderella Story
PHP CLI: A Cinderella StoryMike Lively
 
PL-SQL DIFFERENT PROGRAMS
PL-SQL DIFFERENT PROGRAMSPL-SQL DIFFERENT PROGRAMS
PL-SQL DIFFERENT PROGRAMSraj upadhyay
 

Similaire à Defensive programming in Javascript and Node.js (20)

Your Library Sucks, and why you should use it.
Your Library Sucks, and why you should use it.Your Library Sucks, and why you should use it.
Your Library Sucks, and why you should use it.
 
5 Tips for Better JavaScript
5 Tips for Better JavaScript5 Tips for Better JavaScript
5 Tips for Better JavaScript
 
Operationalizing Clojure Confidently
Operationalizing Clojure ConfidentlyOperationalizing Clojure Confidently
Operationalizing Clojure Confidently
 
Sane Async Patterns
Sane Async PatternsSane Async Patterns
Sane Async Patterns
 
2013-06-15 - Software Craftsmanship mit JavaScript
2013-06-15 - Software Craftsmanship mit JavaScript2013-06-15 - Software Craftsmanship mit JavaScript
2013-06-15 - Software Craftsmanship mit JavaScript
 
2013-06-24 - Software Craftsmanship with JavaScript
2013-06-24 - Software Craftsmanship with JavaScript2013-06-24 - Software Craftsmanship with JavaScript
2013-06-24 - Software Craftsmanship with JavaScript
 
2 Years of Real World FP at REA
2 Years of Real World FP at REA2 Years of Real World FP at REA
2 Years of Real World FP at REA
 
Beautiful PHP CLI Scripts
Beautiful PHP CLI ScriptsBeautiful PHP CLI Scripts
Beautiful PHP CLI Scripts
 
Dutch PHP Conference 2013: Distilled
Dutch PHP Conference 2013: DistilledDutch PHP Conference 2013: Distilled
Dutch PHP Conference 2013: Distilled
 
Subtle Asynchrony by Jeff Hammond
Subtle Asynchrony by Jeff HammondSubtle Asynchrony by Jeff Hammond
Subtle Asynchrony by Jeff Hammond
 
Java 8
Java 8Java 8
Java 8
 
Kamil witecki asynchronous, yet readable, code
Kamil witecki asynchronous, yet readable, codeKamil witecki asynchronous, yet readable, code
Kamil witecki asynchronous, yet readable, code
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
Go Replicator
Go ReplicatorGo Replicator
Go Replicator
 
Groovy
GroovyGroovy
Groovy
 
Playing With Fire - An Introduction to Node.js
Playing With Fire - An Introduction to Node.jsPlaying With Fire - An Introduction to Node.js
Playing With Fire - An Introduction to Node.js
 
Writing Macros
Writing MacrosWriting Macros
Writing Macros
 
Building resilient services in go
Building resilient services in goBuilding resilient services in go
Building resilient services in go
 
PHP CLI: A Cinderella Story
PHP CLI: A Cinderella StoryPHP CLI: A Cinderella Story
PHP CLI: A Cinderella Story
 
PL-SQL DIFFERENT PROGRAMS
PL-SQL DIFFERENT PROGRAMSPL-SQL DIFFERENT PROGRAMS
PL-SQL DIFFERENT PROGRAMS
 

Plus de Ruben Tan

Basic distributed systems principles
Basic distributed systems principlesBasic distributed systems principles
Basic distributed systems principlesRuben Tan
 
Demystifying blockchains
Demystifying blockchainsDemystifying blockchains
Demystifying blockchainsRuben Tan
 
Banking on blockchains
Banking on blockchainsBanking on blockchains
Banking on blockchainsRuben Tan
 
Consensus in distributed computing
Consensus in distributed computingConsensus in distributed computing
Consensus in distributed computingRuben Tan
 
Leveraging zeromq for node.js
Leveraging zeromq for node.jsLeveraging zeromq for node.js
Leveraging zeromq for node.jsRuben Tan
 
Client-side storage
Client-side storageClient-side storage
Client-side storageRuben Tan
 
Distributed app development with nodejs and zeromq
Distributed app development with nodejs and zeromqDistributed app development with nodejs and zeromq
Distributed app development with nodejs and zeromqRuben Tan
 
How we git - commit policy and code review
How we git - commit policy and code reviewHow we git - commit policy and code review
How we git - commit policy and code reviewRuben Tan
 
NodeHack #2 - MVP
NodeHack #2 - MVPNodeHack #2 - MVP
NodeHack #2 - MVPRuben Tan
 
40 square's git workflow
40 square's git workflow40 square's git workflow
40 square's git workflowRuben Tan
 
Unit testing for 40 square software
Unit testing for 40 square softwareUnit testing for 40 square software
Unit testing for 40 square softwareRuben Tan
 

Plus de Ruben Tan (11)

Basic distributed systems principles
Basic distributed systems principlesBasic distributed systems principles
Basic distributed systems principles
 
Demystifying blockchains
Demystifying blockchainsDemystifying blockchains
Demystifying blockchains
 
Banking on blockchains
Banking on blockchainsBanking on blockchains
Banking on blockchains
 
Consensus in distributed computing
Consensus in distributed computingConsensus in distributed computing
Consensus in distributed computing
 
Leveraging zeromq for node.js
Leveraging zeromq for node.jsLeveraging zeromq for node.js
Leveraging zeromq for node.js
 
Client-side storage
Client-side storageClient-side storage
Client-side storage
 
Distributed app development with nodejs and zeromq
Distributed app development with nodejs and zeromqDistributed app development with nodejs and zeromq
Distributed app development with nodejs and zeromq
 
How we git - commit policy and code review
How we git - commit policy and code reviewHow we git - commit policy and code review
How we git - commit policy and code review
 
NodeHack #2 - MVP
NodeHack #2 - MVPNodeHack #2 - MVP
NodeHack #2 - MVP
 
40 square's git workflow
40 square's git workflow40 square's git workflow
40 square's git workflow
 
Unit testing for 40 square software
Unit testing for 40 square softwareUnit testing for 40 square software
Unit testing for 40 square software
 

Dernier

Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
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
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
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
 
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
 
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
 
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
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
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
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
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
 
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
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
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 Scriptwesley chun
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
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
 

Dernier (20)

Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
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
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
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
 
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
 
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?
 
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
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
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...
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
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
 
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
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
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
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
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
 

Defensive programming in Javascript and Node.js

  • 1. Defensive Programming in Javascript & node.js Wednesday, May 29, 13
  • 2. INTRODUCTION Ruben Tan Long Zheng 陈龙正 VP of Engineering, OnApp CDN KL Lead Engineer, 40 Square Sdn Bhd Javascript > 5 years @roguejs Organizer of Nodehack KL Wednesday, May 29, 13
  • 5. Internal dependencies Libraries require(), include() External dependencies Services, files, databases, etc socket.connect(), db.open() DEPENDENCY TYPES Wednesday, May 29, 13
  • 6. NEVER ASSUME! Never assume a dependency is reliable! var db = require(‘database’); db.open(); db.write(‘foo bar’, function (err, data) { // ... do something ... }); Wednesday, May 29, 13
  • 7. NEVER ASSUME! var db = require(‘database’); db.open(); db.write(‘foo bar’, function (err, data) { // ... do something ... }); What if this failed? will write() throw an error? will open() throw an exception? Wednesday, May 29, 13
  • 8. NEVER ASSUME! var db = require(‘database’); db.open(function (err) { db.write(‘mr-big’, bigData, function (err, data) { // ... unrelated logic db.close(); }); db.read(‘foo2’, function (err, data) { // ... some work done }); }); Accidents happen... Wednesday, May 29, 13
  • 9. NEVER ASSUME! var db = require(‘database’); db.open(function (err) { db.write(‘mr-big’, bigData, function (err, data) { // ... unrelated logic db.close(); }); db.read(‘foo2’, function (err, data) { // ... some work done }); }); close() might affect read() Wednesday, May 29, 13
  • 10. A MORE COMPLEX EXAMPLE... Wednesday, May 29, 13
  • 13. DEPENDENCY AWARENESS What can fail, WILL FAIL! Never assume a dependency is reliable! Contingency plans - failover, redundancy, fail-fast, etc Pro-active monitoring Load test, stress test, chaos monkey, etc Remember, what can fail, WILL FAIL! Wednesday, May 29, 13
  • 15. JAVASCRIPT MASTERY Code Execution Order Sanitization & Validation Scope Control Flow Wednesday, May 29, 13
  • 17. EXECUTION ORDER var mq = require(‘mq’); mq.conn(...); mq.on(‘ready’, function () { mq.send(‘batman’); mq.on(‘message’, function (msg) { console.log(msg); mq.close(); }); }); mq is never closed! send() executes before on() Wednesday, May 29, 13
  • 18. DOIN’ IT RIGHT! var mq = require(‘mq’); mq.conn(...); mq.on(‘ready’, function () { mq.on(‘message’, function (msg) { console.log(msg); mq.close(); }); mq.send(‘batman’); }); Swap places Wednesday, May 29, 13
  • 19. SANITIZATION & VALIDATION function foodForKittens(num) { return num * 10; } foodForKittens(); num is not validated, is undefined this will fail! Wednesday, May 29, 13
  • 21. SANITIZATION & VALIDATION var db = require(‘database’); var conn = db.open(...); function writeToDb(conn, cb) { conn.write(bigData, function (err, res) { if (err) { cb(err); return; } cb(null, res); }); }); writeToDb(conn, ghostCallback); Wednesday, May 29, 13
  • 23. var db = require(‘database’); var conn = db.open(...); function writeToDb(conn, cb) { conn.write(bigData, function (err, res) { if (err) { cb(err); return; } cb(null, res); }); }); writeToDb(conn, ghostCallback); what if open() returned undefined? this will throw an exception! Wednesday, May 29, 13
  • 24. var db = require(‘database’); var conn = db.open(...); function writeToDb(conn, cb) { conn.write(bigData, function (err, res) { if (err) { cb(err); return; } cb(null, res); }); }); writeToDb(conn, ghostCallback); What if ghostCallback is undefined? These will fail too! Wednesday, May 29, 13
  • 25. DOIN’ IT RIGHT! var db = require(‘database’); var conn = db.open(...); function writeToDb(conn, cb) { if (typeof conn !== ‘object’) { // ... handle error ... } if (typeof cb !== ‘function’) { // ... handle error ... } conn.write(bigData, function (err, res) { if (err) { cb(err); return; } cb(null, res); }); }); writeToDb(conn, ghostCallback); Validate your input, especially when they involve functions or methods that you need to invoke in your code. These are not the time to fail-fast! Wednesday, May 29, 13
  • 26. DON’T GO OVERBOARD... Validate only necessary parameters Method invocations (anObject.method()) Function invocations (aFunction()) Have a proper error/exception handling policy Validate for correctness, not existence Correctness: typeof a === ‘object’ Existence: a !== undefined Wednesday, May 29, 13
  • 27. SCOPE AWARENESS Plagues most callback-based code Bad practice leads to costly debugging waste New JS programmers not aware of scoping JS scoping is a simple but weird thing (to non-JS programmers) Wednesday, May 29, 13
  • 28. SCOPE!!! var a = ‘outside’; if (true) { var a = ‘inside’; console.log(a); } console.log(a); What is the output? > node test.js inside inside Wednesday, May 29, 13
  • 29. SCOPE!!! Non-JS programmers: a inside the if block is “inside” a outside the if block is “outside” JS programmers: they are both “inside” JS scope by function Wednesday, May 29, 13
  • 30. SCOPE CHAINS!!! var avar = 1; (function outer1() { var avar = 2; (function inner1() { var avar = 3; console.log(avar); // outputs 3 })(); (function inner2() { console.log(avar); // outputs 2 })(); })(); (function outer2() { (function inner3() { console.log(avar); // outputs 1 })(); })(); inner1() local - found! inner2() local - nope outer1() - found! inner3() local - nope outer2() - nope global - found! Wednesday, May 29, 13
  • 31. HOISTING VARIABLES function () { for (var i = 0; i < 10; i++) { for (var j = 0; j < 10; j++) { // ... do something } } } function () { var i, j; // now the scope is clear for i & j for (i = 0; i < 10; i++) { for (j = 0; j < 10; j++) { // ... do something } } } Below is far clearer what individual variable scopes are: Wednesday, May 29, 13
  • 32. CONTROL FLOW Node.js’ async nature makes it unintuitive to predict control flow I <3 async (github.com/caolan/async) Control flow is ugly. Welcome to Javascript. Async will save your life. Use it. Wednesday, May 29, 13
  • 33. CONTROL FLOW var fs; fs = require(‘fs’); fs.readFile(‘./myfile.txt’, function (err, data) { if (err) { console.log(err); return; } fs.writeFile(‘./myfile2.txt’, data, function (err) { if (err) { console.log(err); return; } // ... do stuff ... }); }) Wednesday, May 29, 13
  • 34. CONTROL FLOW Callback hell! Step 1 Step 2 Step 3 Step 4 Step 5 Wednesday, May 29, 13
  • 35. mod.step1(function () { mod.step2(function () { mod.step3(function () { mod.step4(function () { mod.step5(function () { // ... too many levels ... }); }); } }); }); Wednesday, May 29, 13
  • 36. CONTROL FLOW var async, fs; async = require(‘async’); fs = require(‘fs’); async.waterfall([ function step1(callback) { fs.readFile(‘./myfile.txt’, callback); }, function step2(data, callback) { fs.writeFile(‘./myfile2.txt’, data, callback); } ], function (err) { // ... execute something in the end ... }); Wednesday, May 29, 13
  • 38. GOLDEN RULES Golden Rules of Defensive Programming Proper error handling policy Intelligent logging Design for failure Wednesday, May 29, 13
  • 39. ERROR HANDLING Never, ever HIDE errors > node app.js 2>&1 /dev/null ob.callback(function (err, data) { if (err) {} console.log(data); }); socket.on(‘error’, function () {}); Wednesday, May 29, 13
  • 40. ERROR HANDLING I WILL FIND YOU AND I WILL CRASH YOU Wednesday, May 29, 13
  • 41. ERROR HANDLING Standardize error handling in the app Log to error DB Output to error file Output error to a stream Use a logging library Ask a leprechaun to manage it etc Wednesday, May 29, 13
  • 42. LOGGING How do you feel if your “log” looks like this? > tail -f error.log [12:01:55] ERROR - General error detected [12:01:56] ERROR - General error detected [12:01:57] ERROR - General error detected [12:01:58] ERROR - General error detected [12:01:59] ERROR - General error detected [12:02:00] ERROR - General error detected [12:02:01] ERROR - General error detected Wednesday, May 29, 13
  • 44. LOGGING Logs are the first place you go to find out what happened Standardize a log location for each app Make logs easy to access for developers Wednesday, May 29, 13
  • 45. DESIGN FOR FAILURE Common steps to designing software: 1 - what should it do? 2 - how do I do it? 3 - how do I deploy? 4 - done Wednesday, May 29, 13
  • 46. DESIGN FOR FAILURE Proper steps in defensive programming: 1 - what should it do? 2 - how many ways can it fail? 3 - how do I know when it fails? 4 - how do I prevent it from failing? 5 - write code accordingly Wednesday, May 29, 13
  • 47. DESIGN FOR FAILURE Nothing is reliable TCP can fail Network can go down Servers can run out of memory Cows might fly through the sky crashing into your datacenter and flooding the server rooms with milk and destroying everything Wednesday, May 29, 13
  • 48. DESIGN FOR FAILURE Designing for failure mindset & methodologies: Identify SPOF (single point of failures) Redundancy, failover, monitoring Fail-fast, start-fast Persist important data Reliability & Consistency > Speed Code is liability Wednesday, May 29, 13
  • 49. ~ The End ~ Wednesday, May 29, 13