2013-06-15 - Software Craftsmanship mit JavaScript

503 views
416 views

Published on

Entwickeln Sie Clean Code mit JavaScript. Den “Software Craftsman” zeichnen dabei Wissen, Werkzeuge und Wiederholung aus. Diese drei Grundfeste werden speziell für JavaScript beleuchtet. Lernen Sie die wichtigsten Patterns für eine stabile und wartbare Website kennen. Überprüfen Sie Ihre persönliche Werkzeugkiste für Entwicklung, Testing und Deployment. Schließen Sie Bekanntschaft mit Code Katas für JavaScript.

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
503
On SlideShare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
2
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

2013-06-15 - Software Craftsmanship mit JavaScript

  1. 1. Software Craftsmanshipbit.ly/jsCraftsmanshipInteraktive Version der Präsentation!Created by Johannes Hoppe
  2. 2. JohannesHoppe.debit.ly/jsCraftsmanshipInteraktive Version der Präsentation!
  3. 3. PrinzipienWissenWerkzeugeWiederholung
  4. 4. WissenKnow the pitfalls
  5. 5. Implied globalsForgetting varvar foo = function() {bar = 1;};
  6. 6. Boolean type conversionTo Truthy or to Falsy. That is the only question!var el = document.getElementById(does_not_exist);if(el == false) {alert("shouldnt we see this message?!");}
  7. 7. Trailing commaworks on my machine!var foo = {bar: "bar",baz: "baz",};
  8. 8. Return undefinedseñor developers wear mustaches{var foo = function() {return{x : "looks like C# now!"};}
  9. 9. Associative arraysthey dont existvar x = [];x[foo] = "bar";
  10. 10. try .. catch .. finallywho cares about the reason?var foo = function() {try {doCrazyStuff;} catch (e) {return false;}return true;};
  11. 11. Hoistingdeclare upfront all variablesvar foo = "global";var bar = function() {alert(foo);var foo = "local";alert(foo);};
  12. 12. Eval... and the job is donefunction poorMansJsonParser(text) {return eval("(" + text + ")");}var text = { "hello" : "world" } ;var json = poorMansJsonParser(text);
  13. 13. Eval is evil!Never ever!var text = function() { alert("hacked!"); })( ;
  14. 14. Globalsthe mother of all antipatternsfunction foo() {return "bar";}console.log(this[foo]());
  15. 15. Every time you clutter the global namespace,somewhere in the world a helpless kitten dies!
  16. 16. WissenPretty Code
  17. 17. Globalsreduce, minimize, delete or kill them(function() { "wtf?" })();
  18. 18. The switch-casesyndromea functional language wants functions!switch (something) {case 1:doFirst();break;case 2:doSecond();break;case 3:doThird();break;}
  19. 19. Lookup tablesavoid the switch-case syndromevar methods = {1: doFirst,2: doSecond,3: doThird};if (methods[something]) {methods[something]();}
  20. 20. Revealing ModulePatternvar myRevealingModule = function () {var _name = "Johannes";function greetings() {console.log("Hello " + _name);}function setName(name) {_name = name;}return {setName: setName,greetings: greetings};}();» Documentation
  21. 21. Modul loadersuse AMD (require.js)define(test, [jquery], function() {return {saySomething : function() { alert("hello!"); }}});require([test], function(t) {t.saySomething();});
  22. 22. EventsPublish/Subscribe Patternvar $events = $({});$events.bind(somethingHappens, function() {alert("Something happened!");});$events.trigger(somethingHappens);
  23. 23. Werkzeuge
  24. 24. Visual Studio 2010/2012/ F12JScript Editor ExtensionsResharper 7.1JSHintChutzpahFirebug
  25. 25. TDD with Jasmine
  26. 26. Why Jasmine?BDD-style similar to JSpec or RSpec,created by authors of jsUnit and Screw.Unitindependent from any browser, DOM,framework or host languageintegrates into continuous build systems
  27. 27. 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(){
  28. 28. Outputfinished in 0.009s•••••No try/catchJasmine 1.3.1 revision 1354556913Passing5specsPlayershould be able to play a Songwhen song has been pausedshould indicate that the song is currently pausedshould be possible to resumetells the current song if the user has made it a favorite#resumeshould throw an exception if song is already playing
  29. 29. Hello Worldhint: 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();
  30. 30. Wiederholung形形形形
  31. 31. If I would have had time...“ ”
  32. 32. You will never have time!
  33. 33. Learn TDDImprove by self reflectionImprove by feedback of othersHelp others to improveTeach TDDLearn a new language
  34. 34. Test-Driven Development1. Write your tests2. Watch them fail3. Make them pass4. Refactor5. Repeatsee , page 6see , page 62 or many otherGrowing Object-Oriented Software, Guided by TestsWorking Effectively with Legacy Code
  35. 35. 1. Write your testdescribe("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);});});
  36. 36. 2. Watch them failvar saveFormat = function() {return "boo!";};jasmine.getEnv().execute();Demo
  37. 37. 3. Make them passvar 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
  38. 38. 4. Refactorfunction 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
  39. 39. 5. Repeatfunction 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
  40. 40. Deep practicehttp://codekata.pragprog.com/http://katas.softwarecraftsmanship.org/
  41. 41. Danke!blog.johanneshoppe.de

×