320 points · by bjonathan · 15y ago · 199 comments
Edit: I wrote about some of my favorite features of CoffeeScript when we added CoffeeScript support to our CMS app HiFi... http://www.gethifi.com/blog/hosted-cms-coffeescript-support
tl;dr:
1) Lightweight function declarations (with default values!)
2) Implicit Returns
3) Everything is an Expression
4) Object Literal YAML-like syntax
5) Simple, Classical OO Features (you don't have to use them and can still directly access prototypal features, too)
6) (Not in the post) Binding 'this' to the scope's 'this' using => is awesome.
Debugging has not been a problem for me yet, the generated JavaScript is very clean and easy to navigate.
That being said, I'm a Python fan, so I consider significant whitespace to be a feature, not an irritant.
Later I opened the file on Windows (Notepad++) and saw that one line had not been indented, which wasn't showing up on Vim/Gedit. I never tested it to see if that was indeed the problem, I'd already moved on.
if one
if two
two
oops
one
The error given is: Parse error on line 4: Unexpected 'INDENT'Since the compiled JS is just-the-code-I-wrote-myself only in a slightly more verbose curly syntax, troubleshooting my own CS code even when compiled in JS is totally not an issue. Thankfully Coffee does not minify or otherwise obscure the code.
Alas, poor error messages are a big -
# vim: ts=2 sw=2 et :[1] http://metaphysicaldeveloper.wordpress.com/2011/03/31/354/
The CoffeeScript documentation is a fantastic exposition of that: http://jashkenas.github.com/coffee-script/
First of all, I'd like to point out that syntax is not entirely irrelevant, at least not in the sense that CoffeeScript is "just a weird syntax" for JavaScript. Python decorators and list comprehensions are generally thought of as very nice features of the language, but they're really just a nice syntax for higher-order functions and iteration. That syntax makes a big difference. Just adding CoffeeScript's syntax for functions (including the do-operator) and the existential operator would noticeably reduce the size of most JavaScript code, without anything else.
But the difference isn't just syntactic. Here are a few semantic changes in CoffeeScript:
• Everything is an expression (a la Ruby)
• Equality is always strict
• A simplified class-based inheritance model on top of JavaScript's prototypal inheritance
• Switch is almost identical to Ruby's case expression rather than C's switch statement (i.e. clauses don't fall through and it's an expression rather than a statement), which makes it much more useful
I'll put it this way: I've been making websites since 1995 and am fairly proficient in JavaScript, but I have never really liked the language all that much. But CoffeeScript is a joy to use. I actually enjoy programming it, and it's just amazingly readable (both from the nicer syntax and the fact that CoffeeScript's sugar means you don't have to write as much code, and it's easier to understand five lines than 20, even if 15 of the 20 are boilerplate).
The other option is to skip learning javascript properly, which I tried... and it came back hard at me when I tried going beyond enhancing my pages with jquery.
It's what I did. Since I'm already comfortably with Ruby and CoffeeScript's simple syntax, I used CoffeeScript's "Try CoffeeScript" console to insert Ruby-like code and get the Javascript equivalent. Helped me rapidly map Ruby-Javascript equivalences in my head.
Now that I'm quickly comfortable with Javscript's surface and my foot's in the door, diving deeper into the language isn't the obstacle I used to consider it as.
edit: Well listen to the man himself, but I learned tons about JS's semantics by picking up (and picking apart) CS.
Also it's class system and function binding (=>) is something I feel I can no longer live without.
How does coffee script play with existing object oriented JS libraries? Is there compile-time type checking?
To misquote the "Pragmatic Programmer" book... don't use wizard code you don't understand. The opposite applies in my opinion.
https://code.google.com/closure/compiler/docs/js-for-compile...
Life won't get better if interacting with the rest of the world becomes headachery, but thankfully the products in question aren't too hostile to rest of the world. There isn't much of an impedance mismatch between CSS and Sass and following the generated code is easy.
From what little I have written of Coffeescript, it generates clean Javascript and should be easy to follow for anyone who knows Javascript. It's not lifechanging per se but there are things which are much more elegant in Coffeescript.
1) Convenient 'this' binding using =>
2) Lexical scoping. Not much of an issue since I use the 'var' keyword all the time; either that or window.foo or something similar depending on what I am trying to do.
3) I have coded in Python and the "mandatory indentation sans braces" is something I am used to and appreciate. It makes the nested event handling calls prettier.
4) I don't need to use underscore.js while using Coffeescript. The language has some essential feature built-in.
5) The existential operator. From the docs:
"It's a little difficult to check for the existence of a variable in JavaScript. if (variable) ... comes close, but fails for zero, the empty string, and false. CoffeeScript's existential operator ? returns true unless a variable is null or undefined, which makes it analogous to Ruby's nil?"
6) String iterpolation, here docs.
Best of all, there are fewer lines of code to make mistakes in. And fewer stupid "forgot a semicolon" problems.
I'd suggest that people also look at Underscore.js (http://documentcloud.github.com/underscore/) and Backbone.js (http://documentcloud.github.com/backbone/). Same authorship, same quality code, great ideas, great execution.
If you like Sass, you should check out Stylus. Similar, but better. http://learnboost.github.com/stylus/
CSS looks like Assembly code ... you could
write it... but you'd need a damn good reason to
I think LessCSS is better because it keeps syntax compatibility, and you can take an existing CSS file and then gradually improve it. It's also, well, simpler.That said, I can live without the improved CSS features. When I'm working on design-stuff, what really gets in my way is the lack of talent.
As for CoffeeScript, the language looks really interesting, but IMHO, it's just another tool that you need to add to an already HEAVY stack, another tool that breaks and needs special care from time to time, another tool to be learned.
And I'm not sure that CS is so life-changing. Does it fix browser incompatibilities for you? Does it optimize Javascript to run faster? Is it easier to debug? Does it have a kick-ass library that's optimized for it?
IMHO, syntactic sugar (without new paradigms) doesn't get you further than changing your text-editor / adding some newer snippets to it for the boilerplate.
The point of CS is to optimize for developer productivity and happiness, so I think your questions are largely missing the point. It's like asking "well that's a good screwdriver, but does it hammer nails?".
The correct question to ask is: what do I get from this syntactic sugar, and what do I trade. Or to stick with our metaphor:
"What does this screwdriver bring to the table, and does it INTERFERE with the hammering of nails etc?".
So as stated, CS lets you write code faster, express yourself more clearly, and removes headaches common to Javascript. These headaches are problems that are largely not addressed by other tools like jQuery (which have different goals).
To answer your questions:
> Does it fix browser incompatibilities for you
Yes, but only in terms of the language. CS compiles to lowest common denominator Javascript, so you know the compiled code will run just about anywhere.
So you don't have to worry about whether or not the browser's JS engine supports list comprehensions, because you're using CS.
The question is not so much "Does it fix browser incompatibilities for you".... but "Does it introduce browser incompatibilities?". To that, the answer is no.
>Does it optimize Javascript to run faster?
CS allows you to write really expressive code that gets compiled down to simple (but verbose) forms. This has the side-effect that CS code will generally be faster than Vanilla JS code that is written with a similar expressiveness.
In Vanilla JS you would generally have to introduce a library to get the same expressiveness, and that has a run-time penalty. For example: Something that is compiled to a simple for-loop in CS would require a bunch of function calls in a library in vanilla JS, adding a lot of overhead.
CS is not a tool to optimize code, so asking if it optimizes code misses the point. The real question is whether or not it introduces inefficiency, because if it does....that's a drawback that needs to be contrasted to it's benefits.
In this case, no it doesn't...and the code it produces is sometimes faster than similar vanilla JS code.
>Does it have a kick-ass library that's optimized for it?
CS is not meant to fill the same role as a library.
The question is not "does it have a library"...but "what's the implications of using CS vis a vis libraries?" The answer is CS interacts with JS seamlessly, use any library you like.
>Is it easier to debug?
No, because that's not the point of CS. CS is not a debugging tool. The right question is: "is it harder to debug?".
Here we hit what imho is the only real trade-off involved in CS.
Some will hem and haw about having an explicit compilation step; but the tooling support for CS is great and any serious JS developer can fit it into their dev process seamlessly (via commit hooks, watch, build scripts, etc).
Debugging problems is a legit concern, but in my experience it does not add significant problems. Errors in CS syntax are generally caught during compilation and other errors can often be easier to find because the CS code is cleaner and it's easier to catch errors in logic.
I think beginners will often hit problems with debugging and CS because it adds a layer to confuse them. Experienced JS devs on the other hand should be able to cleanly separate the layers and debug them effectively.
The tooling for debugging CS in the future looks promising and will improve the situation.
As for your suggestion that you could just improve your text-editor, use macros, etc....I think that's a good tool to have in your belt but it just doesn't compare to what CS brings to the table.
Either you'd be duplicating CS's efforts ...or you'd not hit the same level of capability...
In the first case, it'd be a pointless re-inventing of the wheel, but your wheel would have drawbacks CS lacks.
With CS there is:
- Lot's of editor support. Your suggestion is tied to 1 editor.
- Lot's of tooling support. There is framework support, and possible browser support in the future...etc etc. Yours would have none, or would need it written.
- Widespread use. Lots of coders will understand my CS code right off the bat, or can learn it easily. Not only will no one understand your crazy macros etc, there's little incentive to learn them.
In the latter case, it's not a valid comparison.
The real question here is what does CS bring to the table, and what do you trade for it. CS had demonstrable benefits and demonstrable drawbacks.
It's my opinion that the benefits dramatically outweigh the drawbacks, but that's a question every developer must ask and answer for themselves.
I get that your contention is somehow, "well if it doesn't do these specific things, it's not 'life changing'", but that seems a pretty arbitrary line to me.
I don't see how you can say developer productivity is not a vital factor in development....and that something that improves productivity, readability, development speed, etc...is not "life-changing", at least as much so as the other factors you mentioned.
When judged in terms of what it's goals are, I think CS is highly effective and far from "pure syntactic sugar" (which to me implies something that simply saves typing).
The point of CS is to optimize for developer
productivity and happiness.
That's a subjective claim that I also think is untrue.CS doesn't have any new paradigms, the type system is the same as Javascript, scoping rules are the same, it's really nothing more than syntactic sugar over JS.
Even Ruby and Python have a lot more differences.
well that's a good screwdriver, but does
it hammer nails
This analogy holds only when you're talking about (a) a screwdriver + (b) a hammer, i.e. totally different tools, with totally different use-cases.Personally I never understood why people use it to make a point.
That means you can use that CSS file provided by the designer directly, and gradually improve it, or you can copy/paste examples given all across the web.
In some cases, that might be a good thing.
(:: Javascript : CoffeeScript) would be a bit of a stretch IMO)
Switching from Rails (et al) to Express (et al) can be a challenging prospect. Not having to give up your floaty modern scripting language syntax is a serious incentive. That aside from the fact that CoffeeScript almost forces you to write better JavaScript.
With Rails these kinds of things (and other things like source layout and such) are just kind of taken care of for you. On the other hand, I'm having a blast doing some CoffeeScript + Node development.
There's a world of difference between fully supporting something and making it your default. Making newcomers jump through hoops to get regular javascript instead of CS (another language in which they may not be familiar) just seems like a poorly thought out plan. As someone pointed out in the GitHub comments; this is just like making HAML and SASS the defaults over HTML & CSS.
I'm not saying anything negative about these libraries; I'm certainly not an authority on them and can't speak to their effectiveness. However, the net result of a default change such as this one is reduced accessibility to newcomers.
Of course, if I'm reading it wrong and this is really just adding support for CoffeeScript to Rails, then disregard everything I just said. :)
Edit: well, don't disregard it--remember it for the future!
I know that you could always change it back to regular JavaScript, but I think many people's experience is that it's almost always recommended to use the defaults when learning a new framework.
I like CoffeeScript, and it does feel Rubyesque, but I just don't support it being the default.
That said, I'm sure a core member will post about the decision, and I almost hope they convince me otherwise. I do really like CoffeeScript, and patio11's comment about HAML/SASS is a good one.
And, again, I absolutely love CoffeeScript and support it 100%. I'm less infatuated with HAML and SASS, but it may simply be that I haven't used them enough. SASS in particular looks very useful.
Regardless, I agree with DHH's tweet yesterday [1] that Rails is a curated set of ideas/technologies. Pretty much by definition it's not one-size-fits-all. I think this is the first time I've found myself on the opposite side of a Rails technology switch decision, which is pretty amazing. I'm looking forward to giving it a chance, and I can always switch back, if it doesn't work out.
For one, CS doesn't abstract away any platform dependance in JS - it is syntactic.
which is fine, just that your argument isn't.
I'm not at all convinced that CoffeeScript has yet matured to the point where it can generate better javascript than any qualified JS developer. Now, it may get there some day--but I don't believe it's there yet.
Moreover, in this case, you're introducing an additional layer of complexity and source of errors--the compile time of CoffeeScript. Maybe it doesn't compile. Maybe it compiles such that the Javascript doesn't do what you intended the javascript to do. Maybe the javascript breaks in some browser environments and there's no way to cleanly work around that problem in CoffeeScript.
Again, it's not that I'm against CS--I'm simply against it being the default. It's an additional can of worms that I don't think the majority of Rails developers are ready and / or willing to open.
This is going to be in your generated Gemfile only. It can still be swapped, removed or replaced as everyone is used to do when it comes to prototype/jquery.
I don't really have an opinion either way as my JS skills are minimal and I know almost nothing about CS.
That aside, yes, I do think you're reading it wrong— since CoffeScript compiles straight into JS, there isn't really any meaningful way for it to "replace" it. It's just adding a layer on top.
I'm sure coffeescript is a fine language in its own right--but the fact that it has to generate Javascript code rather than something lower-level is frustrating to me. I haven't dug into it enough to know; but my gut tells me that (like other examples of code attempting to "compile to another programming language") the output from the "compiler" is less than quality code. Maybe, in most cases, this is fine. In some environments though where performance is at a premium, I don't know that CS will output well optimized code.
BTW, I'm the one who accidentally downvoted you. Sorry about that. I need to be more careful with the clicking.
I guess I'm somewhat out of the loop when it comes to Rails, but why does something written in a scripting language need a scripting language?
It's pretty minor, but you know how nerds get when they smell blood.
Will this confuse new users? Probably not, since the template file is going to include instructions and an explanation. Will the change break any existing sites? I really doubt it.
In the end, encouraging a better default language is a great change. New users are already required to learn to write ERB/Haml to make a Rails app; this is no different, and easily ignored if you're not interested.
It seems like an overly aggressive goal to do both things at once.
If any framework can get away with doing something like this, it'd be Rails.
At any rate, I'm excited about anything that increases CoffeeScript adoption.
[edit] And with SCSS also slated to be the default, it seems consistent with "the Rails way" moving forward.
I'm just disappointed they didn't have the balls to make HAML the default templating engine.
Edit: Rails is also about "sensible defaults." I'm not sure that making CS the default is really the "sensible" choice.
Personally I'm more interested in the real 3.1 goodness: flushed responses. The implementation is fascinating.
http://yehudakatz.com/2010/09/07/automatic-flushing-the-rail...
The same sort of operation as adding/removing a gem from a project.
Chill people.
So in my opinion we had one minor version with JavaScript I could relate to, and now we're back to where we were. But I don't mind, I'll just avoid using it.
Anyway, I agree that Rails core has traditionally been far from the savviest of JavaScript developers, but the nice thing about Rails 3 is that they've finally achieved reasonable modularity with all the components, so there's not much pain in getting around Rails opinions anymore.
As for CoffeeScript, I'm still on the fence, but it's clear that Jeremy Ashkenas knows his JavaScript, and his work is not done out of ignorance, so I'm glad for it to get more exposure.
What is so wrong with writing idiomatic, unobtrusive JS? I personally don't care for JS syntax (compared to the beauty of ruby and haml), but that's life... JS syntax my be ugly, but it can be written elegantly.
CoffeeScript is much more like HAML/SASS in function, and while there are arguments against those in some environments (like if you need to hire a lot of designers without a dev mentality or environment), they've been proven to be very effective in practice, and I'm quite sure CoffeeScript will be the same.
One of the recurring arguments I've seen is that this change will make it harder for people to get started with Rails. I really don't understand how this is the case, because if you understand what public/javascripts is for and what javascript_include_tag does, you should also be able to write normal javascript all day long. Hell, you don't even need that, adding your own HTML to include a script into the page works too (as always). There is no need to write CoffeeScript if you don't want to/don't know how to; write all the js you want.
In reality, the only outcome of this will be more people discovering and learning CoffeeScript. I seriously doubt this will discourage anyone from learning Rails. If it does, they were bound to find something that discouraged them eventually.
I don't like the idea neither I'm a Rails developer, but I think that this will increase the learning curve.
Let it be just a choice.
I like the move, defaults should be used to push forward positive change and very few if anyone seems to have said they would rather not use CoffeeScript.
Of course, all of this stuff makes your life easier once you learn it. I would even be down with making Haml and Sass the default, since most Rails developers seem to use them anyway. Scaffolds would give newbies a good starting point to work with.
(And, come on, list comprehensions in Javascript? Awesome.)
No one is taking away your raw Javascript, it'll work just fine. This just makes it easy for people to use CoffeeScript when they first build an app. It's more of a statement than anything else.
This change definitely has the existing Rails community in mind.
Or as I told my friend: "Given that you already know how to create a blog in 5 seconds, how can we also make you not have to use semicolons in your JS?"
When I go to hire somebody it is a near certainty that they are very proficient with CSS. Sass? Probably less likely. For the sake of argument let's say I could find somebody proficient in Sass, what about all the other boutique technologies I have in my product?
At some point your product can devolve into an opaque and indecipherable hodgepodge of 'cool stuff'. Sometimes it really is better to keep things simple, even though you are causing yourself some personal pain.
Also, this "huge problem" you talk about is the same that people used to argue against Ruby/Rails with. Hey, everyone knows Java/Struts -- let's just keep it simple for hiring drone purposes!
The argument about rails vs struts may have been similar, but I don't think the comparison holds water. Web development frameworks are different than markup and stylesheet standards. We have standards that define HTML, CSS, Javascript, etc. There is no one standard that governs MVC frameworks.
So while I would expect any competent web developer to know HTML, CSS, and Javascript, I would not expect them to be competent in my particular choice of web framework since there is necessarily less standardization in that area.
My core point is that you need to exercise some caution before jumping into all these different technologies with both feet. There are considerations that extend beyond your personal coding pleasure.
Also, my point was not to argue against one single technology. I am arguing against building an application with 20 different gee-whiz packages that causes a nightmare when training new developers.
It is an effective way to make sure you can never be fired from your current job though.
In my current project I take it a step further. I get the CSS from a designer, dump it in an scss partial, include that partial in the main sass/scss file where I then override and add styles. That way I can keep their CSS versioned and untouched while being able to automatically combine it with additional styles into a compressed CSS file.
The point is that there are plenty of ways Sass is incredibly useful even if the main CSS person doesn't work with it directly.
Obviously Coffeescript is a little different, but the advantage is that a Javascript developer is a programmer and it's not an unreasonable expectation for them to be able to get up to speed on Coffeescript.
With SCSS it's even easier, just rename the file and refactor it later if you're feeling lazy.
On a practical note, I've subcontracted out design work before and convinced (strongarmed) the designer to learn SASS. They're usually pretty happy about it.
Another JS framework to look at is Backbone[2].
To create a void function in CoffeeScript, just add a naked "return" as the final line.
sideEffecty = ->
do something
do somethingElse
returnWhile I've written some javascript, I wouldn't say it's very good and I'm not really that well versed in the features of Javascript either.
Would you say it's better to
a) Learn to do Javascript properly then learn CoffeeScript b) Learn CoffeeScript and forget about Javascript?
JavaScript is a weird language, especially if you're coming from a backend language (even dynamic ones like Ruby). Without understanding why things happen in JavaScript (such as: a block doesn't create scope; functions/lambdas do), you won't understand why things are happening in CoffeScript, either.
Debugging is CoffeeScript's biggest weakness; you'll often have to dig into the JavaScript it outputs in order to fix bugs, and (for the moment) you won't necessarily know what line of CoffeeScript maps to which line of output JavaScript. ( I believe this is actively being worked on: https://github.com/jashkenas/coffee-script/issues/558 ).
Here are some good resources that have helped me:
http://yuiblog.com/crockford/ http://eloquentjavascript.net/contents.html http://ejohn.org/apps/learn/#1
I assume their website is the best place to start... (http://www.coffeescript.org)
Wouldn't including CoffeeScript create a new dependency on Java (to run in Rhino or what not) or Node.js? How is the CoffeeScript compiled to JavaScript if this is not the case?
Yes I know, you can change it.
Yes. I know its impact is probably minimal if I don't care for it.
But, I really would like to see a strong argument made for why this should be a default for Rails, especially when SASS and HAML, which have wider adoption and facetime with the Rails community aren't the default (and I think, rightfully so)
All that's happening is by default the scaffolding generator scripts will spit out boilerplate coffeescript rather then boilerplate javascript.
All that's needed to change back is to comment out a single, clearly marked line of code.
If you're on Windows or Mac OS, ExecJS will use the JS runtime already installed on your system (Windows Script Host or Apple JavaScriptCore). You can also install a gem like therubyracer (V8 for MRI, available on Heroku) or therubyrhino (Rhino for JRuby) for faster compilation. And ExecJS can use Node.js or Spidermonkey if they're installed too.
You'll need CoffeeScript (gem) installed in this situation, but that's just another Rails dependency.
EDIT: I should point out that Rails will use CoffeeScript for client-side (browser) code, not server-side code. That remains Ruby and associated DSLs.
The commits add a dependency to the coffee-script[1] gem, which requires the execjs[2] gem, which requires some way of running JS.
1: https://github.com/josh/ruby-coffee-script 2: https://github.com/sstephenson/execjs
Between yaml, sass (although not scss), haml, and coffescript, is the next step a version of ruby getting rid of end statements in favor of whitespace? I've often dreamed of such a thing.
module Foo
module Bar
class Fubar
def boom
p "I like monkey patches"
end
end
end
end
Ick! > It's interesting that rails is headed toward whitespace
> significance in all its file formats, yet the most apparent
> difference between ruby and it's main rival Python is that
> whitespace is not significant.
That may be the most obvious difference at first glance, but it's also the most superficial. Idiomatic Python and idiomatic Ruby will be written completely differently.It's been years since Rails had to do any marketing. The Merb merge was about bringing incredible ideas into Rails, and it shows in Rails 3. Similarly, CoffeeScript is being defaulted because DHH believes it's a better way to write JS. He has better things to do than make contrived technical decisions to stir up controversy. If you disagree than I pity your paranoia.