SlideShare ist ein Scribd-Unternehmen logo
1 von 49
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Andere mochten auch

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
 

Andere mochten auch (13)

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
 

Ähnlich wie 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
 

Ähnlich wie 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
 

Mehr von 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
 

Mehr von 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
 

Kürzlich hochgeladen

DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontologyjohnbeverley2021
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Zilliz
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
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
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
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
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 

Kürzlich hochgeladen (20)

DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
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
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
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
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 

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