CoffeeScript & Jasmine - MadJS February 2012


Published on

Published in: Technology
  • CoffeeScript: Accelerated JavaScript Development ---
    Are you sure you want to  Yes  No
    Your message goes here
  • CoffeeScript in Action ---
    Are you sure you want to  Yes  No
    Your message goes here
  • The Little Book on CoffeeScript ---
    Are you sure you want to  Yes  No
    Your message goes here
No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide
  • \n
  • First, an introduction:\n* I’m Matt Gauger\n
  • \n
  • * I work at Bendyworks\n * We primarily do Ruby on Rails work, with some iOS now.\n * We care very deeply about software craftsmanship and honing our agile practices.\n\n
  • Which leads me to my dilemma\n
  • Are you familiar with impostor syndrome? It's the idea that even very skilled practitioners may sometimes feel like an impostor due to over-emphasizing their weaknesses.\nFurther, it’s the inability to internalize your own accomplishments.\n
  • I felt like an impostor when it came to JavaScript.\n * I could read and write the syntax, pull in jQuery, manipulate the DOM, etc.\n * I had several projects under my belt at this time that used AJAX and were fairly complex\n * I'd even read JavaScript: The Good Parts several times, taken notes, etc.\n
  • \n
  • brings us back to my thesis:\n
  • But before that: Let me warn you that I'm not going to go over every piece of syntax here.\nI'm not going to be able to teach you all of CoffeeScript or Jasmine in this talk.\nFor that, see the resources & books at the end of the talk.\n\n
  • \n
  • 2010 I learn about CoffeeScript, and it sort of looks like Ruby and Python.\nIt grabs my interest.\nBut at that point it's still a novelty: The compiler is in Ruby, no one uses it for real dev yet.\nIt was a *toy*\n
  • Flash-forward to today, and everyone is extolling CoffeeScript.\nIt comes with Rails 3 by default now and gets compiled on the fly into JS for your app.\nI’ve been using CoffeeScript for about a year now, but not full time.\n
  • So why use CoffeeScript? What are its good parts?\n* It restricts you to a subset of JS you’d recognize from JS: The Good Parts.\n* It puts JSLint & a compiler between me and the half dozen browsers I need to support\n* It warns me when I do something wrong\n
  • This might be the most important part of the talk, and reason to use CoffeeScript\nIf you’re like me, you’ll put the compiled JS up next to the CoffeeScript\nBy reading the output of the compiler, you’re learning what good JS looks like.\n
  • It's not what runs in the browser.\nDifficult to debug => Finding bugs (Names are the same between CoffeeScript & JS; its readable)\nMay feel like you’re learning a whole different language (It’s not, it’s less verbose JS)\n
  • At this point we may want to differentiate between bugs that are caused by poor syntax and mistakes (mistake bugs), and bugs that come from the interaction between complicated data & edge cases (ie computer is in a state you didn't predict when you wrote the code)\nCoffeeScript can help cut down on a lot of the former.\n\n
  • \n
  • This will print it’s true happily.\nThat’s not quite what you expect when the data is more complicated than 1 and the string 1.\nType coercion is the number 1 reason for WTF JS\n
  • Ok, so that’s a very simple example.\nBut how often are you going to get bitten by more complicated versions of that same bug?\nAnd are you always going to remember to use triple equals? === I am now.\n
  • \n
  • \n
  • JS and CoffeeScript have “lexical scope”\n
  • \n
  • \n
  • Hopefully this is better than ‘null’, but you could do worse and just not initialize it at all.\nJavaScript won’t force you to initialize it, but doing so can help you to figure out scope issues.\n
  • the ?= is syntactic sugar, the ? is called the existential operator in CoffeeScript\nCombined with =, the existential operator means “a equals b unless a?” or\n “Let b be the default value for a.”\n\n\n
  • CoffeeScript can wrap each compiled file into a scope\nThis may be the default, depending on the version of coffeescript you’re using - option now.\nThis is actually pretty cool -- if you’re including a lot of JavaScripts on a website, you can’t mix scope there -- no accidental leakage into the global scope space.\n
  • \n
  • You write list comprehensions rather than for loops in CoffeeScript\nComprehensions are expressions, and can be returned and assigned\n
  • CoffeeScript allows “reasonably solid” JavaScript developers to accomplish the latter by simply writing the former.\n\n
  • \n
  • \n
  • I started using Jasmine last summer on a client project.\nIt’s enough like the BDD tool we use in Rails, Cucumber, that I consider it a BDD tool.\nIt makes the most sense to me of the BDD/TDD tools in JS I’ve used\n
  • All code should be tested => that’s what I believe.\nYou can spend some up-front time testing your code, or you can spend a lot of time bug fixing later\nI realize that not all legacy codebases are going to be TDD overnight.\n
  • \n
  • \n
  • Better? Not really. But we can see what the syntax is doing here\nand I’m using a real assertion!\n
  • \n
  • \n
  • to make it easier to test the logic, things like AJAX calls, etc\nwithout interacting with the DOM\n
  • it just so turns out, that the abstraction for testing is a better abstraction overall\n
  • You can still do this in Jasmine, in fact, I find it kind of natural.\n
  • This means you don’t need jQuery and you don’t need to run it in a real browser (but you can)\n
  • \n
  • \n
  • You can use after Each to run a teardown function after each successful test\nIf you need a teardown function after a test whether it passed or failed, use after()\n
  • In Ruby, we’ve been doing mocking and stubbing for awhile.\nJasmine’s spies make it easy!\nThese let you do things like watch to see if a method was called\nOr to stub out other methods so you don’t do real AJAX calls, etc.\n
  • So you’re thinking, CoffeeScript and Jasmine sound great, but I have a legacy codebase.\nI’ll never get to use either; and they don’t help my big legacy codebase.\nWell, we’ve run into this and I have a plan.\n
  • First, get your tools lined up.\nGet the CoffeeScript compiler in your tool chain, and get Jasmine set up and passing a dummy test.\nYou still haven’t done anything with your legacy code at this point.\n
  • It all starts with one bug. Or one feature, if you’re feeling adventurous. \nYou might not be able to pull out an entire feature and rewrite it. I understand that.\nThe way to start this is to write a test around the bug and see it fail. (this might be hard -> DOM)\nThen fix the bug in regular old JavaScript. See the Jasmine test pass.\n
  • You’ve got a working test around this bug.\n(You know the test works because you saw it red then green.)\nNow’s your chance to rewrite it in CoffeeScript. It may only be one function at this point. That’s ok.\n
  • We found that even with a legacy codebase of a lot of JavaScript, we were able to figure out logical chunks that should live together in CoffeeScript files.\n
  • This is the hardest part.\nThe temptation is there to just give up and fix bugs only in JS, not to write unit tests, etc.\nThe other temptation is the one you usually can’t give into, which is to try to rewrite everything all at once -> this rarely is accomplishable, it’s better to stage the changes.\n
  • \n
  • \n
  • \n
  • CoffeeScript & Jasmine - MadJS February 2012

    1. 1. HowCoffeeScript &Jasmine mademe a better JSdeveloper
    2. 2. I’m Matt Gauger
    3. 3. @mathiasx
    4. 4. I work atBendyworks
    5. 5. My dilemma:
    6. 6. Impostor Syndrome
    7. 7. I was aJavaScriptimpostor
    8. 8. So, what does this have to do with CoffeeScript?
    9. 9. My thesis:
    10. 10. How CoffeeScript & Jasminemade me a better JSdeveloper(and how it can help you,too)
    11. 11. CoffeeScript
    12. 12. History
    13. 13. Today
    14. 14. CoffeeScript has Good Parts?
    15. 15. CoffeeScript: JavaScript:
    16. 16. CoffeeScript: JavaScript: ^ Major Win ^
    17. 17. Criticisms ofCoffeeScript
    18. 18. That isnt to say thatCoffeeScripteliminates all bugs.
    19. 19. Some examples:
    20. 20. Coercing the wrong type if (1 == 1) { console.log("its true!");}
    21. 21. CoffeeScript:if 1 is ‘1’ console.log ‘never true!’Compiles to:if (1 === ‘1’) { console.log("never true!");}
    22. 22. Scope
    23. 23. CoffeeScript scope isessentially the same as in JS
    24. 24. 1. Every function creates a scope, andthe only way to create a scope is todefine a function.2. A variable lives in the outermostscope in which an assignment has beenmade to that variable.3. Outside of its scope, a variable isinvisible.
    25. 25. The neat thing is thatCoffeeScript’s compilerplaces the vars foreach scope at the topof that scope
    26. 26. For example, this compiled CoffeeScript: var singCountdown;singCountdown = function(count) { var singBottleCount, singDecrement; singBottleCount = function(specifyLocation) { var bottleStr, locationStr; // ... } // ...}
    27. 27. Define a variable ata specific scope bygiving it a sensible initial value
    28. 28. a ?= bis one way to give a default
    29. 29. Lastly, wrapping up your code.
    30. 30. Compiled CoffeeScript Example:(function() { console.log “hello world!”;}).call(this);
    31. 31. Simpler Looping
    32. 32. Jeremy Ashkenas’s ExampleLoop over every item in a list, in CoffeeScript: for item in list process itemIntention gets obscured by managing the loop, in JS: for (var i = 0, l = list.length; i < l; i++) { var item = list[i]; process(item); }
    33. 33. CoffeeScript will help you:•Write OO, Prototype-based code•Avoid bugs in comparisons •Stop using ==, only use ===•Manage scope and avoid state through scope creep•Reduce off-by-one errors in looping, and generally write better loops than you were writing before
    34. 34. Jasmine
    35. 35. (My) History(with Jasmine)
    36. 36. Why Jasmine?
    37. 37. The example on the site:describe("Jasmine", function() { it("makes testing awesome!", function() { expect(yourCode).toBeLotsBetter(); });});
    38. 38. This example sucks!
    39. 39. describe (addition, function () {      it(adds two numbers, function () {          expect(1 + 2).toEqual(3);      });  });
    40. 40. How should we test JS?
    41. 41. Functions should notdepend on the DOM
    42. 42. Our logic needs tobe in separate pieces
    43. 43. Easier to test = better code
    44. 44. Follow TDD/BDD:red, green, refactor
    45. 45. Jasmine is designed to be standalone
    46. 46. Some really coolfeatures of Jasmine:
    47. 47. Matchers:•.toBe()•.toBeNull()•.toBeTruthy()•.toBeDefined()•.toBeUndefined()•etc.
    48. 48. Setup and Teardown:•beforeEach()•afterEach()
    49. 49. Spies: built-inmocking & stubbing
    50. 50. But what aboutlegacy codebases?
    51. 51. Start simple.
    52. 52. Fix one bug.(red, green, refactor)
    53. 53. Rewrite the affectedcode in CoffeeScript.
    54. 54. Start grouping in files / modules.
    55. 55. Keep improving the codebase.
    56. 56. Lessons Learned:•These tools can help you learn JS better.•Legacy codebases can slowly grow better through using CoffeeScript & Jasmine.•Taking advantage of these is up to you!
    57. 57. Thanks!
    58. 58. Resources to learn more:••••