found_drama


Would anybody want it?


    Archive for the “Code” category

    #10 things I love about Sass

    CSS. Verbose, repetitive, rife with bizarre quirks.

    Can’t say that I’m a fan. On the web, you’re using it out of necessity. Even the CSS masters out there must admit, there has got to be something better.

    Fortunately, there’s Sass. A super-set of CSS, it helps to eliminate some of CSS’s most obnoxious aspects during the development lifecycle. By way of example, my ten favorite parts about Sass:

    1. Nesting. Let’s get the most obvious one out of the way first. You know how CSS makes you write stuff like this:
      #container .post code,
      #container .post tt,
      #container .post pre {
      	font-family: Consolas, Courier, monospace;
      }
      

      Well, Sass will lets you do that like this:

      #container .post {
      	code, tt, pre {
      		font-family: Consolas, Courier, monospace;
      	}
      }
      
    2. Nesting. Again? (you say)—check this out. Whereas CSS would require this:
      .styledText {
      	font-family: Georgia, Times, serif;
      	font-style: oblique;
      }
      

      In Sass you can do this:

      .styledText {
      	font: {
      		family: Georgia, Times, serif;
      		style: oblique;
      	}
      }
      

      More lines perhaps, but it feels less verbose. And more manageable.

    3. Includes. CSS already has this notion of an @import rule, and while Sass overrides borrows the directive (with a twist on the exact syntax), it goes a step further. While the CSS @import results in an extra http request for the imported stylesheet, Sass will auto-concatenate the files—getting the request down to one. (And as a side-benefit, reducing your CSS build/deploy phases down to just calling Sass on your scss file(s).)
      /* CSS: */
      @import url("_reset.css");
      
      /* Sass: */
      @import "reset";
      
    4. Variables. Totally missing from CSS, Sass brings these to the table. Observe:
      $theme_accent: #771100;
      $theme_bg: #222222;
      
      #container {
      	h1, h2, h3 { color: $theme_accent; }
      	.post {
      		border: {
      			$accent_border: 1px $theme_accent;
      			$dark_border: 1px $theme_bg;
      
      			top: $accent_border;
      			left: $accent_border;
      			bottom: $dark_border;
      			right: $dark_border;
      		}
      	}
      }
      

      Need I go on?

    5. Line comments. Again: // need I go on?
    6. Mixins. Like variables on steroids. The Sass site’s example is great; I’ll reproduce here:
      @mixin rounded-top {
      	$side: top;
      	$radius: 10px;
      
      	border-#{$side}-radius: $radius;
      	-moz-border-radius-#{$side}: $radius;
      	-webkit-border-#{$side}-radius: $radius;
      }
      
      #navbar li { @include rounded-top; }
      #footer { @include rounded-top; }
      

      And did I mention that you can set up your mixins to take arguments?

    7. Validation. This shouldn’t be hot shit, but it is. If you’ve been screwing around with CSS long enough, you’ve likely run into a situation where some rule you’ve written isn’t taking and you can’t figure out why and it turns into a two-hour wild goose chase only to discover that you fat-fingered border as boarder or failed to close a curly bracket or some such thing. Your IDE might be warning you. But Sass goes a step further and puts the error message right into your page—right there at the top where you can’t ignore it. (It’s also a useful error message.)
    8. Auto-minification. This is right up there with, and arguably part of Includes. Either way, depending on how you have your Sass compiler set up, you can have it crunch the CSS output, stripping all comments and extraneous whitespace[1].
    9. SassScript functions. As if the variables and mixins weren’t enough for you, there’s also a whole host of hot functions and operations that you can perform in “SassScript”. For example, Dan Rubin recently Tweeted:
      CSS needs to allow me to write: * { saturation:+15%; }

      And of course, Sass has almost exactly this:

      $my_color: #77110;
      .post-title { color:  saturate($my_color, 15%); }
      

      …and a whole bunch of other color functions. Among other functions.

    10. Directives, control statements, and other functions. Maybe just more of the same from the SassScript functions above, but damn is there some great material here.
      article {
      	$base_font_size: 12px;
      	$base_line_height: $base_font_size * 1.5;
      
      	font-size: $base_font_size;
      	line-height: $base_line_height;
      
      	/* simple math */
      	h1 { font-size: $base_font_size * ($base_line_height + 1em); }
      	h2 { font-size: $base_font_size + 4px; }
      }
      
      /* some looping with conditional logic */
      @for $i from 1 through 10 {
      	#flickr_badge_image#{$i} {
      		@if $i % 2 == 0 {
      			color: 3993FF;
      		} @else {
      			color: #ff1c92;
      		}
      	}
      }
      

    All this amazing power… and I have just been casually exploring Sass over the past couple days. This project is a treasure trove and I hope that it is here to stay. My hat is off to the folks working on Sass. Marvelous work.

    1. Granted, your mileage may vary on the download time savings from this kind of minification in a CSS file. After all, provided that you’re stripping your comments from your production CSS, most the file’s trivial bytes are whitespace and gzip basically does away with that overhead. []

    #on syntax highlighting: a brief public service announcement

    In preparation for an up-coming post[1], I did a bit of extra legwork on syntax highlighting plugins for WordPress and wound up switching from Google Syntax Highlighter for WordPress (GSHW)[2] to SyntaxHighlighterPro. Both of them are backed by Alex Gorbatchev’s Syntax Highlighter library. But more on that in a moment.

    What prompted the switch was the fact that I noticed that GSHW was mangling some CSS syntax highlighting operations. The regex used to grab hex colors was getting greedy and highlighting #id-selectors as if they were colors[3]. After a little digging, I came to discover that GSHW was using a quite-out-of-date version of Gorbatchev’s library.

    Exploring the Syntax Highlighter site a bit, I found a couple of other plugins that appeared to be more up-to-date. I gave a crack at SyntaxHighlighter Evolved and the above mentioned SyntaxHighlighterPro. Both had more recent versions[4] of the library baked in. Both seemed a step up in that regard, but I went with -Pro because it was going to require the fewest tweaks and changes[5] in the code samples already posted[6] and also because its control panel offered the ability to toggle specific syntaxes at will.

    That said, the “Evolved” plugin has a nice suite of options.

    This is likely just a temporary stop-gap measure, however. I may pull the plug on the plugins and just drop in Gorbatchev’s script directly—the latest version appears to offer on-demand loading of the “brush” scripts. Combine that with a minified version of the script and that may prove a better overall solution than the plugins can offer.

    Nevertheless, the problem remains that the CSS highlighter “brush” script needs some work. It doesn’t really seem to recognize common selectors (#id and .class selectors, I’m looking at you)… and this bugs me.

    But until then…

    1. Quite likely the next post… []
    2. Which I’ve been using for a few months now. []
    3. Meaning that it was only coloring the hash and the first six characters of #container. []
    4. Though neither was using the most recent version. []
    5. I.e., it more gracefully relented to my efforts to kludge in the AppleScript and Sass support. []
    6. I.e., -Pro recognized the <pre> formatted blocks whereas Evolved was going to require changing all those to use BBCode-style [bracket] syntax. Ick. []

    #an annotated guide to the Google JavaScript Style Guide

    Following up on the Google JavaScript Style Guide that made the rounds recently: I did a couple of passes through the document and absorbed as much of it as I could[1]. After discussing the style guide with a few peers, I thought that it might make sense to provide some annotations—in part for personal reference[2] but also to engage in the dialogue. There are a few implicit points in there that I thought might be interesting to pull together. And I also felt comfortable indulging in the hubris of splitting hairs.

    And so, without further ado: an annotated guide to the Google JavaScript Style Guide:

    Read the rest of this entry »

    1. Nutshell version of my reaction: Well that all seems like common sense, just spelled out rather eloquently; but I’ll be damned if you want me give up my double-quotes. []
    2. To aid with digestion. []

    #The Joy of Clojure

    In the realm of technical, programming-related, computer science-type books, The Joy of Clojure is a bit of an oddity. And this is a very good thing.

    WHAT THE BOOK IS NOT: The Joy of Clojure is not a beginner’s introduction to the language. The Joy of Clojure is not a glorified appendix of methods and syntax. The Joy of Clojure is not a “cookbook” or a “how-to” or an “FAQ”. The Joy of Clojure is not an explanation on how to shoe-horn your Java code into (some (graceful [parenthetical syntax])). The Joy of Clojure is not a dry or sterile technical manual.

    WHAT THE BOOK IS: The Joy of Clojure is as much a philosophical text as it is a survey of the language. The Joy of Clojure embraces the language’s own flexible nature and describes itself in that way. The Joy of Clojure has a sense of humor. The Joy of Clojure expects a little work from you (but is willing to lend a hand along the way). The Joy of Clojure respects the baggage that you bring from your other programming languages, but expects you to check those bags at the door. The Joy of Clojure wants to make you a better programmer, not a Clojure programmer.

    Rating? ★★★★☆

    So… why 4-stars? I seldom give out 5-star reviews—I reserve those for books that completely blow my mind. While this one was a real eye-opener, my lid did not pop fully and totally off. Why not? Partly because I’m coming into Clojure as an outsider. It isn’t a book for Clojure beginners—you could be a Clojure novice and get a lot out of this book, but I believe you would need a little more background in Lisp[1]. How to get that 5th star…? A “chapter 0″ for the complete novice? or maybe an appendix that can help that novice wade through some of the more esoteric-feeling elements of the language.—i.e., folks such as myself that are unfamiliar with Clojure (and/or Lisp in a more general sense[2]) may find the language’s syntax a bit… opaque? oblique? There’s a learning curve with every language, I suppose but there are certain things in Clojure that look FUNDAMENTALLY WRONG to someone accustomed to a language like JavaScript or Java. The onus is (of course) on the reader to embrace these things (i.e., “Who is the one that opened the book and wanted to learn something new?”) but it’s sometimes easy to get lost in these little details.

    I would absolutely recommend this to anyone I know that had an interest in Clojure and/or functional programming.

    1. Lisp’s syntax can be a bit off-putting to outsiders and novices… and the authors even come out and say this in the book. []
    2. Viz., I haven’t looked at/used Lisp in probably… 10 years? []

    #why you should basically never use the Number constructor

    Inspired by some recent entanglements with a vendor’s API:

    var n = new Number(1);
    alert(n);				// 1
    typeof n;				// object
    n instanceof Number;	// true
    
    var nn = 1;
    alert(nn);				// 1
    typeof nn;				// number
    n instanceof Number;	// false
    
    n == nn;				// true
    
    typeof n == typeof nn;	// false
    
    n++;
    nn++;
    alert(n);				// 2
    alert(nn);				// 2
    
    n == nn;				// true
    
    typeof n;				// number
    typeof nn;				// number
    typeof n == typeof nn;	// true
    

    The type coercion will ultimately work in your favor but the main point is that the type coercion has to take place in the first place. Granted, it is probably an edge case[1] to do something like:

    var n = new Number(x); // where x is a global storing an incrementer
    
    function doMath(a){
    	if (typeof a == "number") {
    		return a + x;
    	}
    }
    

    …but you never know. There’s some strange code out there[2].

    1. And therefore you get what you deserve? []
    2. And by that I mean: Don’t be one of the ones writing it. []

    #faking it: static method calls in JavaScript

    Have you ever wanted (as an object-oriented JavaScript developer) to work with an object before you had an instance of it? For example, perhaps there’s a method that you would like to call without going through the overhead of instantiating the object[1]. How would you go about doing this? Can you invoke myWidget.doSomeStuff() if you don’t have an instance of myWidget yet? Do we have static methods in JavaScript like we do in (for example) Java[2]? (HINT: the short answer is “not exactly”.)

    First: what are the more traditional options?

    A global function. If the mechanics of the function are not specific to the object’s implementation, then this might be a perfectly acceptable approach. If your function is just “doing stuff to” (or “…with”) some arguments then this might be fine. Performing some mathematical operations? Who needs an object-oriented approach for determining Fibonacci numbers? Or trimming whitespace from strings? Certainly that would be overkill.

    A namespaced util method. Not too dissimilar from the global function approach; but if you’re namespacing, you’re less likely to have collisions in your variable and function names, and maybe some better sharing of common code, etc[3]. As far as “static methods” go, we’re just calling these methods off a singleton—fine (for example) for converting constants, or otherwise working with and manipulating known quantities.

    But what about something more sophisticated? What if you have a family of classes (e.g., widget editors) that are all related but may each require an ever so slightly different approach to the context inspection? A global function or namespaced util won’t quite cut it here. What are we to do?

    Now it turns out that JavaScript’s prototypal inheritance apparatus provides us with a way to do this. Depending on how you’ve designed and implemented your object classes[4], this could be a relatively trivial operation.

    Observe (using our suggested example above):

    // the "usual" way...
    
    // (1a) init your class and assign to a variable:
    var myWidget = new net.fd.SomeWidget();
    	// now we have our instance
    
    // (1b) call the method from your instance:
    myWidget.inspectContext();
    	// ...except inspectContext() tells returns false
    	// meaning that we created myWidget for nothing
    
    // (2) try something a little different
    net.fd.SomeWidget.inspectContext();
    	// error! - "inspectContext" is undefined
    	// ...because "net.fd.SomeWidget" is the constructor
    
    // (3) try it again, with a twist
    net.fd.SomeWidget.prototype.inspectContext();
    	// still returns false but this time we didn't have
    	// the extra overhead of creating the instance

    Nifty, eh?

    Imagine a scenario where you have a few dozen classes like this (e.g., each class representing an editor for a specific widget that you might deploy to your WordPress-based blog)—using this technique, each class could perform its own inspection of the context (e.g., the DOM fragment representing the widget) and depending on the outcome of the inspection, assign itself as the appropriate handler[5]—and all without creating an instance of a given class until it is needed[6]. Marvelous!

    But this approach is not without some dangers[7] and does require careful attention to detail and some discipline. Because you’re invoking the specified method from the prototype, you should assume that the method is not “scope safe”. This is not to say that this is unsafe; but this might not be what you think it is[8]. You can[9] still tap into this in your “static” method, but you better be damn certain that your this is what you need it to be and that whatever it is you’re trying to access was declared as part of that object’s prototype. As for the method itself, the arguments passed to the function become of critical importance[10] for how the method returns. But, if you are aware of the possible scope issues, and engineer the “static” method in such a way that it is sufficiently scope agnostic, then invoking methods from the prototype in this manner can be a powerful technique to add to your JavaScript repertoire.

    1. …only to find out that it’s not even the right object for the task! []
    2. For the record, I’m a Java neophyte; this is the comparison explained to me, and the one that makes sense. []
    3. But now we’re just talking “best practices”. []
    4. I won’t go into prototypal inheritance and the various JavaScript constructor patterns here—it’s too big of a subject for this footnote (or even this particular blog post). However, may I recommend familiarizing yourself with “parasitic combination inheritance”, which you may recognize as the extend() method from frameworks such as Ext JS or YUI. For a great overview of inheritance and constructor patterns, may I recommend chapter 6 of Nicholas Zakas’ Professional JavaScript for Web Developers []
    5. We’re (of course?) assuming here that there is a 1:1 binding relationship between editors and widgets for the sake of this example. []
    6. Granted, in this example, there still needs to be some apparatus in place to manage calling the inspector method from each prototype (bringing us right back around to the “global function and/or namespaced util” question) but depending on the specifics of the implementation, there’s actually an opportunity to cache or curry the results from the inspection. And/but this is not at all to diminish the huge advantage you get from having the class’ method actually on the class; everything you need to know about the class is that it exists (and it takes care of the rest). []
    7. As many JavaScript developers have discovered by their “journeyman” stage, messing around with the prototype of a given object is not for the faint of heart. []
    8. That is to say, if you think this is an instance, then you’d be mistaken—and you’d be missing the whole point of trying this method in the first place. []
    9. …and for maximum effectiveness probably should. []
    10. But when aren’t the arguments important…? []

    #my remarkable ability to summarize

    The product of the last two months of programming, depicted h... on Twitpic


    #review: High Performance JavaScript

    While reading Nicholas Zakas’ High Performance JavaScript, it occurred to me that there were actually two different reviews that I wanted to write. So, rather than try to reconcile them into one review, I’ll simply apply them here as an ordered list.

    (1) To continue with the JavaScript University metaphor (from my review of Zakas’ Professional JavaScript for Web Developers): Finals are coming up in Prof. Crockford’s upper-division JavaScript class. You’ve been a diligent student all semester and although you’re not failing, it always seems like you’re somewhere in the middle of the pack. You want desperately to ace the final exam, so you reach out for some help. Zakas (the graduate student/teaching assistant for the class) offers to show you the thesis he is working on. Then It hits you like a bolt from the blue — every bit of it resonates with you. “It’s so simple! so clear!” you exclaim. The inner machinations of the language snap together in a way that makes it all feel new and exciting — the possibilities are boundless! You go back over your notes. You were close — oh so close — the whole time. But the last little bits drop in. A refinement here, a re-factor there… and the next thing you know, things are blazing. Your pages load 60% faster, execution time is down an average of 40%. You’re amazed at yourself. And when the grades for the final exam come back, you’re pleased to see that you aced it (aside from that little Oops on scoping closures — but you try to think of that as a conscious trade-off). Prof. Crockford is pleased (if a little disappointed that it took you this long to Get It) and you’re the envy of your peers. At least until next semester’s RegEx class with Prof. Levithan.  [Rated: ★★★★★]

    (2) The frustrating part about working at a well-organized shop is that you get yourself all excited for a book like this and then half the recommendations in there are things that you’re already doing. Put scripts at the bottom of the document? Check. Minify and compress? Check. Concatenate and package? Check. So on the one hand you say: “I guess I can sleep a little easier at night knowing that our build system adheres to the best practices recommended by the experts out there.” But on the other hand, you’re a little disappointed because you were hoping for some startling revelations. Again: not that this makes it without merit. From this perspective, what is noteworthy about this book is that these best practices and techniques are all gathered up in one place and presented in a logical order; even if “you’re already doing it right”, it is still a worthwhile exercise to meditate on the specifics, and to really go deep on why these best practices are important. (Plus, it’s great to see the data — nothing beats a little chartporn for proving the point.) [Rated: ★★★★]


    #my new JavaScript vade mecum

    While I was reading this, I liked to imagine that I was at university and that Douglas Crockford was the insanely popular genius professor that showed up late for lectures, and then either spoke too fast or else mumbled a lot, and then locked himself in his office refusing to answer the door during office hours while he worked on his Next Big Thing that would make everyone oooh and aaah and validate his brilliance.  Meanwhile, in that same imaginary university, Nicholas Zakas was the graduate student that served as the TA to that class—and he happened to be equally brilliant and super-accessible and willing to take the time out to explain it all in a way that was thorough and comprehensible.

    So that being said, if you consider yourself or would like to consider yourself a professional front-end engineer for web applications (or in any way want to become a JavaScript expert), I cannot recommend this book enough.  On the one hand, you have Crockford’s The Good Parts—which does a great job of eviscerating JavaScript while at the same time extracting its (well…) its Good Parts—but it’s like someone ran the text through a minification utility and made it tokenized and super-dense and stripped out all the comments.  And on the other hand, you have Zakas’ Professional JavaScript for Web Developers which one might describe as The Good Parts (the long version).

    What Zakas gives us—while assuming that you are already doing some professional JavaScript web development—is a good overview of JavaScript/ECMAScript, with special care given to make the text practical.  This is not strictly an academic exercise; he is careful to make sure that each example applies to real world scenarios (i.e., web apps running in a browser) and that you are able to take away something useful and meaningful from the text’s discussion.  In other words, he provides a road map for how to make the most of JavaScript as a language[1] and how to make it work in all the convoluted, counter-intuitive situations that you are basically guaranteed to encounter[2].

    In a nutshell, if you are doing professional web development on the front end, this book needs to be on your desk.  I can’t wait to check out his next book[3]

    BONUS ROUND: Zakas says that Wrox has made this book available as a DRM-free ebook.

    DOUBLE BONUS ROUND: Apparently, I made the man laugh.

    TRIPLE BONUS ROUND: Shout from the man himself, albeit with a pointer to this review as it appears on Amazon.

    1. …since, as a front-end engineer on the web, you’re stuck with it. []
    2. Even if you don’t expect to ever work with XML.  Even if you do think that the JavaScript 2 and ECMAScript 4 stuff is a little too future-forward/in-the-weeds type stuff. []
    3. Reading this before Feburary 24, 2010?  Sign up for your chance at a free copy! []

    #getting academic on the JavaScript Array

    An experiment (in part to settle something of academic debate); what is faster new Array() or [][1]?  The function for the test case:

    function makeSomeArrays(){
    	var outputter = function(fn){
    		var ts = new Date().getTime();
    		fn();
    		var te = new Date().getTime();
    		console.log("total time: " + (te-ts)/1000 +
    			" seconds");
    	};
    
    	// 1 million:
    	var L = 1000000;
    
    	// use Array constructor; push L new arrays...
    	var test1 = function(){
    		var a = new Array();
    		for (var i=0; i<l ; i++) {
    			a.push(new Array());
    		}
    	};
    
    	// same as above - but in each case,
    	// declare a length to the array
    	var test2 = function(){
    		var a = new Array(L);
    		for (var i=0; i<L; i++) {
    			a.push(new Array(0));
    		}
    	};
    
    	// same as above but via index assignment
    	var test3 = function(){
    		var a = new Array(L);
    		for (var i=0; i<L; i++) {
    			a[i] = new Array(0);
    		}
    	};
    
    	// for 4-6: replace Array constructor w/ Array literal
    	// notation except where declaring a length
    	// (container array, 5 + 6)
    	var test4 = function(){
    		var a = [];
    		for (var i=0; i<L; i++) {
    			a.push([]);
    		}
    	};
    
    	var test5 = function(){
    		var a = new Array(L);
    		for (var i=0; i<L; i++) {
    			a.push([]);
    		}
    	};
    
    	var test6 = function(){
    		var a = new Array(L);
    		for (var i=0; i<L; i++) {
    			a[i] = [];
    		}
    	};
    
    	var tests = [test1, test2, test3, test4, test5, test6];
    
    	for (var j=0; j<tests.length; j++) {
    		console.info("test #" + (j+1) + ":");
    		outputter(tests[j]);
    	}
    }

    Yes, I realize that test #2 and test #5 result in an array with a length of 2,000,000 (vs. 1,000,000 for the other 4 tests).

    Now for some chart porn; results:

    As usual in these kinds of performance tests, shorter bars mean better/faster performance.  (And yes, test case #5 was wildly out-of-scale when run in Firefox[2].)

    Test case #3 wins out in Firefox (1.536 seconds), but test case #6 wins in both Chrome and Safari (0.313 and 0.397 seconds, respectively).  Interestingly, Safari out-performed Chrome in 4 of the 6 test cases; but Chrome came out on top overall with that 0.313 second figure for test case #6.  The trick seems to be in assigning a length to the array and then assigning values to the indices instead of just pushing the values onto the end.

    But this seems to wind up not answering the original question about Array() vs. [].  So really quickly (in Chrome), I re-ran test #6 with a new “test #7″ that replaced a[i] = [] with a[i] = new Array().  Console output:

    test #6:
    total time: 0.405 seconds
    test #7:
    total time: 0.892 seconds

    Oh wait… that was basically the same as test #3…  Hooray for Array literals!

    1. Knowing full well that it’s never as simple as that. []
    2. Due in large part to the fact that it paused execution to request my intercession.  But that doesn’t exactly bode well anyway, does it? []



    Creative Commons License This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License.