SlideShare a Scribd company logo
Software Craftsmanship
bit.ly/jsCraftsmanship
Interaktive Version der Präsentation!
Created by Johannes Hoppe
JohannesHoppe.de
bit.ly/jsCraftsmanship
Interaktive Version der Präsentation!
PrinzipienWissen
Werkzeuge
Wiederholung
WissenKnow the pitfalls
Implied globals
Forgetting var
var foo = function() {
bar = 1;
};
Boolean type conversion
To Truthy or to Falsy. That is the only question!
var el = document.getElementById('does_not_exist');
if(el == false) {
alert("shouldn't we see this message?!");
}
Trailing comma
works on my machine!
var foo = {
bar: "bar",
baz: "baz",
};
Return undefined
señor developers wear mustaches
{
var foo = function() {
return
{
x : "looks like C# now!"
};
}
Associative arrays
they don't exist
var x = [];
x['foo'] = "bar";
try .. catch .. finally
who cares about the reason?
var foo = function() {
try {
doCrazyStuff;
} catch (e) {
return false;
}
return true;
};
Hoisting
declare upfront all variables
var foo = "global";
var bar = function() {
alert(foo);
var foo = "local";
alert(foo);
};
Eval
... and the job is done
function poorMansJsonParser(text) {
return eval("(" + text + ")");
}
var text = ' { "hello" : "world" } ';
var json = poorMansJsonParser(text);
Eval is evil!
Never ever!
var text = ' function() { alert("hacked!"); })( ';
Globals
the mother of all antipatterns
function foo() {
return "bar";
}
console.log(this['foo']());
Every time you clutter the global namespace,
somewhere in the world a helpless kitten dies!
WissenPretty Code
Globals
reduce, minimize, delete or kill them
(function() { "wtf?" })();
The switch-case
syndrome
a functional language wants functions!
switch (something) {
case 1:
doFirst();
break;
case 2:
doSecond();
break;
case 3:
doThird();
break;
}
Lookup tables
avoid the switch-case syndrome
var methods = {
1: doFirst,
2: doSecond,
3: doThird
};
if (methods[something]) {
methods[something]();
}
Revealing Module
Pattern
var myRevealingModule = function () {
var _name = "Johannes";
function greetings() {
console.log("Hello " + _name);
}
function setName(name) {
_name = name;
}
return {
setName: setName,
greetings: greetings
};
}();
» Documentation
Modul loaders
use AMD (require.js)
define('test', ['jquery'], function() {
return {
saySomething : function() { alert("hello!"); }
}
});
require(['test'], function(t) {
t.saySomething();
});
Events
Publish/Subscribe Pattern
var $events = $({});
$events.bind('somethingHappens', function() {
alert("Something happened!");
});
$events.trigger('somethingHappens');
Werkzeuge
Visual Studio 2010/2012
/ F12
JScript Editor Extensions
Resharper 7.1
JSHint
Chutzpah
Firebug
TDD with Jasmine
Why Jasmine?
BDD-style similar to JSpec or RSpec,
created by authors of jsUnit and Screw.Unit
independent from any browser, DOM,
framework or host language
integrates into continuous build systems
Jasmine Bootstrap
<!DOCTYPEhtml>
<html>
<head>
<title>JasmineSpecRunner</title>
<linkrel="stylesheet"href="lib/jasmine-1.3.1/jasmine.css"/>
<scriptsrc="lib/jasmine-1.3.1/jasmine.js"></script>
<scriptsrc="lib/jasmine-1.3.1/jasmine-html.js"></script>
<!--includesourcefileshere...-->
<scriptsrc="src/Player.js"></script>
<scriptsrc="src/Song.js"></script>
<!--includespecfileshere...-->
<scriptsrc="spec/SpecHelper.js"></script>
<scriptsrc="spec/PlayerSpec.js"></script>
<script>
(function(){
varhtmlReporter=newjasmine.HtmlReporter();
varjasmineEnv=jasmine.getEnv();
jasmineEnv.addReporter(htmlReporter);
jasmineEnv.specFilter=function(spec){
returnhtmlReporter.specFilter(spec);
};
varcurrentWindowOnload=window.onload;
window.onload=function(){
Output
finished in 0.05s
•••••
No try/catch
Jasmine 1.3.1 revision 1354556913
Passing5specs
Player
should be able to play a Song
when song has been paused
should indicate that the song is currently paused
should be possible to resume
tells the current song if the user has made it a favorite
#resume
should throw an exception if song is already playing
Hello World
hint: press F12 and paste this code!
var helloWorld = function() {
return "Hello World!";
};
describe('helloWorld', function() {
it('says hello', function() {
expect(helloWorld()).toEqual("Hello World!");
});
});
jasmine.getEnv().execute();
Wiederholung
形
形
形形
If I would have had time...
“ ”
You will never have time!
Learn TDD
Improve by self reflection
Improve by feedback of others
Help others to improve
Teach TDD
Learn a new language
Test-Driven Development
1. Write your tests
2. Watch them fail
3. Make them pass
4. Refactor
5. Repeat
see , page 6
see , page 62 or many other
Growing Object-Oriented Software, Guided by Tests
Working Effectively with Legacy Code
1. Write your test
describe("saveFormat", function () {
var original = '{0} - {1} - {2}';
it("should replace placeholders", function () {
var expected = 'A - B - C';
var formated = saveFormat(original, 'A', 'B', 'C');
expect(formated).toEqual(expected);
});
it("should encode injected content", function () {
var expected = 'A - &lt;b&gt;TEST&lt;/b&gt; - C';
var formated = saveFormat(original, 'A', '<b>TEST</b>', 'C');
expect(formated).toEqual(expected);
});
});
2. Watch them fail
var saveFormat = function() {
return "boo!";
};
jasmine.getEnv().execute();
Demo
3. Make them pass
var saveFormat = function(txt) {
$(arguments).each(function (i, item) {
if (i > 0) {
item = ($('<div/>').text(item).html());
txt = txt.replace("{" + (i - 1) + "}", item);
}
});
return txt;
};
jasmine.getEnv().execute();
Demo
4. Refactor
function htmlEncode(input) {
return ($('<div/>').text(input).html());
}
var saveFormat = function(txt) {
$.each(arguments, function (i, item) {
if (i > 0) {
item = htmlEncode(item);
txt = txt.replace("{" + (i - 1) + "}", item);
}
});
return txt;
};
jasmine.getEnv().execute();
Demo
5. Repeat
function htmlEncode(input) {
return ($('<div/>').text(input).html());
}
var saveFormat = function() {
var args = Array.prototype.slice.call(arguments);
var txt = args.shift();
$.each(args, function (i, item) {
item = htmlEncode(item);
txt = txt.replace("{" + i + "}", item);
});
return txt;
};
jasmine.getEnv().execute();
Demo
Deep practice
codekata.pragprog.com
katas.softwarecraftsmanship.org
Danke!
blog.johanneshoppe.de

More Related Content

PPTX
PHP 5 Magic Methods
PDF
Justjava 2007 Arquitetura Java EE Paulo Silveira, Phillip Calçado
PDF
Magic methods
PPTX
Dan Shappir "JavaScript Riddles For Fun And Profit"
PDF
JavaScript Design Patterns
PDF
Headless Js Testing
PDF
Powerful JavaScript Tips and Best Practices
PDF
Your code sucks, let's fix it! - php|tek13
PHP 5 Magic Methods
Justjava 2007 Arquitetura Java EE Paulo Silveira, Phillip Calçado
Magic methods
Dan Shappir "JavaScript Riddles For Fun And Profit"
JavaScript Design Patterns
Headless Js Testing
Powerful JavaScript Tips and Best Practices
Your code sucks, let's fix it! - php|tek13

What's hot (20)

PDF
Ten useful JavaScript tips & best practices
ZIP
Lisp Macros in 20 Minutes (Featuring Clojure)
PDF
FalsyValues. Dmitry Soshnikov - ECMAScript 6
PDF
Writing clean code
PDF
Bottom Up
PDF
Javascript - The Good, the Bad and the Ugly
PDF
(ThoughtWorks Away Day 2009) one or two things you may not know about typesys...
PDF
Fundamental JavaScript [UTC, March 2014]
ODP
Javascript
PPTX
Clean Code Development
PPTX
JavaScript 1 for high school
PPT
New syntax elements of java 7
PDF
How DRY impacts JavaScript performance // Faster JavaScript execution for the...
PDF
Your code is not a string
PDF
Design Patterns in PHP5
PPTX
Php & my sql
PDF
New methods for exploiting ORM injections in Java applications
ZIP
Yes, But
PDF
A Re-Introduction to JavaScript
PDF
Ten useful JavaScript tips & best practices
Lisp Macros in 20 Minutes (Featuring Clojure)
FalsyValues. Dmitry Soshnikov - ECMAScript 6
Writing clean code
Bottom Up
Javascript - The Good, the Bad and the Ugly
(ThoughtWorks Away Day 2009) one or two things you may not know about typesys...
Fundamental JavaScript [UTC, March 2014]
Javascript
Clean Code Development
JavaScript 1 for high school
New syntax elements of java 7
How DRY impacts JavaScript performance // Faster JavaScript execution for the...
Your code is not a string
Design Patterns in PHP5
Php & my sql
New methods for exploiting ORM injections in Java applications
Yes, But
A Re-Introduction to JavaScript
Ad

Viewers also liked (6)

PDF
2011-12-13 NoSQL aus der Praxis
PDF
DMDW 8. Student Presentation - Groovy to MongoDB
PDF
2013-03-23 - NoSQL Spartakiade
PPTX
Ria 03 - Hello ASP.NET MVC
PDF
2013 05-03 - HTML5 & JavaScript Security
PPTX
Ria 09 trends_and_technologies
2011-12-13 NoSQL aus der Praxis
DMDW 8. Student Presentation - Groovy to MongoDB
2013-03-23 - NoSQL Spartakiade
Ria 03 - Hello ASP.NET MVC
2013 05-03 - HTML5 & JavaScript Security
Ria 09 trends_and_technologies
Ad

Similar to 2013-06-24 - Software Craftsmanship with JavaScript (20)

PDF
Building a JavaScript Library
PDF
Intro to JavaScript Testing
PPTX
Building maintainable javascript applications
KEY
JavaScript Neednt Hurt - JavaBin talk
PDF
JavaScript Abstraction
PPTX
All of javascript
PPTX
Java scriptforjavadev part2a
PPT
JavaScript Needn't Hurt!
PDF
How do I write Testable Javascript?
PDF
How do I write Testable Javascript
PDF
How do I write testable javascript?
PDF
Painless Javascript Unit Testing
PDF
Java script core
PDF
AngularJS Beginner Day One
PPTX
All of Javascript
PPTX
Prototype Framework
PPTX
JS Essence
PPTX
Javascript basics
KEY
JavaScript Growing Up
PPTX
Angular JS in 2017
Building a JavaScript Library
Intro to JavaScript Testing
Building maintainable javascript applications
JavaScript Neednt Hurt - JavaBin talk
JavaScript Abstraction
All of javascript
Java scriptforjavadev part2a
JavaScript Needn't Hurt!
How do I write Testable Javascript?
How do I write Testable Javascript
How do I write testable javascript?
Painless Javascript Unit Testing
Java script core
AngularJS Beginner Day One
All of Javascript
Prototype Framework
JS Essence
Javascript basics
JavaScript Growing Up
Angular JS in 2017

More from Johannes Hoppe (20)

PDF
2017 - NoSQL Vorlesung Mosbach
PPTX
NoSQL - Hands on
PDF
Einführung in Angular 2
PDF
MDC kompakt 2014: Hybride Apps mit Cordova, AngularJS und Ionic
PPTX
2015 02-09 - NoSQL Vorlesung Mosbach
PDF
2012-06-25 - MapReduce auf Azure
PDF
2013-06-25 - HTML5 & JavaScript Security
PDF
2013-06-15 - Software Craftsmanship mit JavaScript
PDF
2013 02-26 - Software Tests with Mongo db
PDF
2013-02-21 - .NET UG Rhein-Neckar: JavaScript Best Practices
PDF
2012-10-16 - WebTechCon 2012: HTML5 & WebGL
PDF
2012-10-12 - NoSQL in .NET - mit Redis und Mongodb
PDF
2012-09-18 - HTML5 & WebGL
PDF
2012-09-17 - WDC12: Node.js & MongoDB
PDF
2012-08-29 - NoSQL Bootcamp (Redis, RavenDB & MongoDB für .NET Entwickler)
PDF
2012-05-14 NoSQL in .NET - mit Redis und MongoDB
PDF
2012-05-10 - UG Karlsruhe: NoSQL in .NET - mit Redis und MongoDB
PDF
2012-04-12 - AOP .NET UserGroup Niederrhein
PDF
2012-03-20 - Getting started with Node.js and MongoDB on MS Azure
PDF
2012-01-31 NoSQL in .NET
2017 - NoSQL Vorlesung Mosbach
NoSQL - Hands on
Einführung in Angular 2
MDC kompakt 2014: Hybride Apps mit Cordova, AngularJS und Ionic
2015 02-09 - NoSQL Vorlesung Mosbach
2012-06-25 - MapReduce auf Azure
2013-06-25 - HTML5 & JavaScript Security
2013-06-15 - Software Craftsmanship mit JavaScript
2013 02-26 - Software Tests with Mongo db
2013-02-21 - .NET UG Rhein-Neckar: JavaScript Best Practices
2012-10-16 - WebTechCon 2012: HTML5 & WebGL
2012-10-12 - NoSQL in .NET - mit Redis und Mongodb
2012-09-18 - HTML5 & WebGL
2012-09-17 - WDC12: Node.js & MongoDB
2012-08-29 - NoSQL Bootcamp (Redis, RavenDB & MongoDB für .NET Entwickler)
2012-05-14 NoSQL in .NET - mit Redis und MongoDB
2012-05-10 - UG Karlsruhe: NoSQL in .NET - mit Redis und MongoDB
2012-04-12 - AOP .NET UserGroup Niederrhein
2012-03-20 - Getting started with Node.js and MongoDB on MS Azure
2012-01-31 NoSQL in .NET

Recently uploaded (20)

PDF
A comparative analysis of optical character recognition models for extracting...
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
Electronic commerce courselecture one. Pdf
PDF
Encapsulation theory and applications.pdf
PPTX
Cloud computing and distributed systems.
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Machine learning based COVID-19 study performance prediction
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
cuic standard and advanced reporting.pdf
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PPTX
Machine Learning_overview_presentation.pptx
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PPTX
Big Data Technologies - Introduction.pptx
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Approach and Philosophy of On baking technology
A comparative analysis of optical character recognition models for extracting...
Network Security Unit 5.pdf for BCA BBA.
Advanced methodologies resolving dimensionality complications for autism neur...
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Electronic commerce courselecture one. Pdf
Encapsulation theory and applications.pdf
Cloud computing and distributed systems.
The AUB Centre for AI in Media Proposal.docx
Review of recent advances in non-invasive hemoglobin estimation
Machine learning based COVID-19 study performance prediction
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
cuic standard and advanced reporting.pdf
Dropbox Q2 2025 Financial Results & Investor Presentation
Machine Learning_overview_presentation.pptx
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
Big Data Technologies - Introduction.pptx
Building Integrated photovoltaic BIPV_UPV.pdf
“AI and Expert System Decision Support & Business Intelligence Systems”
Approach and Philosophy of On baking technology

2013-06-24 - Software Craftsmanship with JavaScript