• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
CoffeeScript & Jasmine - MadJS February 2012
 

CoffeeScript & Jasmine - MadJS February 2012

on

  • 5,842 views

 

Statistics

Views

Total Views
5,842
Views on SlideShare
2,630
Embed Views
3,212

Actions

Likes
5
Downloads
17
Comments
0

10 Embeds 3,212

http://blog.mattgauger.com 2901
http://mathias.github.com 160
http://localhost 64
http://coderwall.com 45
http://goingon.in 19
http://posterous.com 14
http://webcache.googleusercontent.com 3
http://www.feedspot.com 3
http://cloud.feedly.com 2
http://paper.li 1
More...

Accessibility

Categories

Upload Details

Uploaded via as Apple Keynote

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • \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 CoffeeScript & Jasmine - MadJS February 2012 Presentation Transcript

  • HowCoffeeScript &Jasmine mademe a better JSdeveloper
  • I’m Matt Gauger
  • @mathiasx
  • I work atBendyworks
  • My dilemma:
  • Impostor Syndrome
  • I was aJavaScriptimpostor
  • So, what does this have to do with CoffeeScript?
  • My thesis:
  • How CoffeeScript & Jasminemade me a better JSdeveloper(and how it can help you,too)
  • CoffeeScript
  • History
  • Today
  • CoffeeScript has Good Parts?
  • CoffeeScript: JavaScript:
  • CoffeeScript: JavaScript: ^ Major Win ^
  • Criticisms ofCoffeeScript
  • That isnt to say thatCoffeeScripteliminates all bugs.
  • Some examples:
  • Coercing the wrong type if (1 == 1) { console.log("its true!");}
  • CoffeeScript:if 1 is ‘1’ console.log ‘never true!’Compiles to:if (1 === ‘1’) { console.log("never true!");}
  • Scope
  • CoffeeScript scope isessentially the same as in JS
  • 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.
  • The neat thing is thatCoffeeScript’s compilerplaces the vars foreach scope at the topof that scope
  • For example, this compiled CoffeeScript: var singCountdown;singCountdown = function(count) { var singBottleCount, singDecrement; singBottleCount = function(specifyLocation) { var bottleStr, locationStr; // ... } // ...}
  • Define a variable ata specific scope bygiving it a sensible initial value
  • a ?= bis one way to give a default
  • Lastly, wrapping up your code.
  • Compiled CoffeeScript Example:(function() { console.log “hello world!”;}).call(this);
  • Simpler Looping
  • 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); }
  • 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
  • Jasmine
  • (My) History(with Jasmine)
  • Why Jasmine?
  • The example on the site:describe("Jasmine", function() { it("makes testing awesome!", function() { expect(yourCode).toBeLotsBetter(); });});
  • This example sucks!
  • describe (addition, function () {      it(adds two numbers, function () {          expect(1 + 2).toEqual(3);      });  });
  • How should we test JS?
  • Functions should notdepend on the DOM
  • Our logic needs tobe in separate pieces
  • Easier to test = better code
  • Follow TDD/BDD:red, green, refactor
  • Jasmine is designed to be standalone
  • Some really coolfeatures of Jasmine:
  • Matchers:•.toBe()•.toBeNull()•.toBeTruthy()•.toBeDefined()•.toBeUndefined()•etc.
  • Setup and Teardown:•beforeEach()•afterEach()
  • Spies: built-inmocking & stubbing
  • But what aboutlegacy codebases?
  • Start simple.
  • Fix one bug.(red, green, refactor)
  • Rewrite the affectedcode in CoffeeScript.
  • Start grouping in files / modules.
  • Keep improving the codebase.
  • 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!
  • Thanks!
  • Resources to learn more:•http://jashkenas.github.com/coffee-script/•http://pivotal.github.com/jasmine/•http://pragprog.com/book/tbcoffee/coffeescript•http://js2coffee.org/