Archive

Archive for December, 2009

JavaScript Mock Objects

December 23rd, 2009

While testing a library I’m writing I found that I needed to pass in a simple mock object with a small set of methods and track how many times and with what values each of the methods gets called.

The following snippet of code is what I came up with.

function mock() {
    var mockMethods = arguments;
 
    var dummy = {}
    dummy.calls = [];
 
    for (var i=0; i< mockMethods.length; i++) {
        var methodName = mockMethods[i];
        dummy.calls[methodName] = [];
        dummy[methodName] = (function(methodName) {
            return function() {
                //Convert function arguments into an array
                var args = [];
                for (var i=0; i<arguments.length; i++) 
                    args[i] = arguments[i];
 
                this.calls[methodName].push(args);               
            }
        })(methodName);
    }
 
     return dummy;
}

And in an qunit test I’d use it like this:

test("fills rect when bounds and fillStyle are good", function() {
    var n = new PNode({
        bounds: new PBounds(0, 0, 20, 20),
        fillStyle: "rgb(255,0,0)"
    });
 
    var mockCtx = mock("fillRect");
    n.paint(mockCtx);
 
    same(mockCtx.calls.fillRect[0], [0,0,20,20]);
})

I hope someone finds this useful.

Agile Development, JavaScript , , ,

Google Analytics Trick

December 22nd, 2009

It’s not much, but the following jQuery trick allows me to track all outbound links on the site without modifying each and everyone of them.

try {
  var pageTracker = _gat._getTracker(TRACKER_CODE_HERE);
  pageTracker._trackPageview();
 
  $(function() {
    $("a").click(function() {
      var href = this.href;
      if (href.toString().indexOf("SITE_DOMAIN_HERE") == -1) {
        pageTracker._trackPageview('/outgoing/'+href.substring(7));
      }      
    });
  })
} catch(err) {
}

JavaScript , ,

Easy, Simple, Wrong

December 17th, 2009

<rant>
Hey everyone, you can’t simplify indefinitely so stop trying so square the circle!

I’m not saying stop trying to simplify things, just stop once there’s a minimal and acceptable level of complexity. If you dumb it down too much, it’s plain wrong.

Once you’ve reached that point, either you leave well enough alone, or add to it by organizing things. More often than not organizing will actually degrade runtime performance but will decrease development time. If you’re not happy with that, maybe development isn’t for you. You’re likely going to prefer messes and will spend too much time shifting crap around instead than dealing with it.
</rant>

Sorry about that. :)

General, Ideas, Programming, Rants ,

Client-Side JavaScript DSLs

December 14th, 2009

This blog post is about solving one of my JavaScript paint points; specifically its verbosity when defining inline functions. The way in which I solve it is interesting to me and hopefully to someone else too.

Here goes…

Why not do DSLs on the client side by compiling to JavaScript in a compiler written in JavaScript?

I realize that doing a “true compiler” is computationally expensive, but the leaps in JavaScript performance we’ve seen lately make it tractable.

To do the job with the respect it deserves, you need to build a full parse tree, but for my particular DSL, a replacement scheme that relies on regular expressions should do fine except in the pathological cases. Except for obfuscated code, I have yet to find a piece of code that uses commas to separate expressions for example.

So, what do I have in mind?

I love the JavaScript language, but its format for defining lambda expressions is nasty. You’re forced to insert the function keyword where (except for pathological cases) it could be inferred from its context. This wouldn’t bother me at all if I wasn’t required to define them so often while working with jQuery.

For those who are visual, this is the code I’d like to write:

<script type="text/x-javascript">
$({ 
  alert("Hello"); 
 
  $("a").click((e) { 
    alert("clicked"); 
  });
 
  $.post("testing.php", {a: 100, b:100}, (result) { 
    alert("Result is: " + result);
  });
});
</script>

And this is the code I have to write right now:

<script type="text/javascript">
$(function() { 
  alert("Hello"); 
 
  $("a").click(function (e) { 
    alert("clicked"); 
  });
 
  $.post("testing.php", {a: 100, b:100}, function(result) { 
    alert("Result is: " + result);
  });
});
</script>

Now, it’s not a big change, but it’s definitely worth it as your jQuery lambda heavy code starts to balloon.

This is how you could make it happen:

  1. Define a script section that uses an “invalid” mime type and place your code there. This will be ignored by the browser, so you won’t get any syntax errors.
  2. Include an external script that searches for scripts of a certain type, converts them, then evaluates.

If you want to see this idea in action take a look here: http://www.machete.ca/x-javascript.html

I can’t be the first person to have thought of this, but I thought I’d tell it on the mountain just incase.

Thoughts?

Ideas, JavaScript, Programming , , ,

Documentation Metrics

December 8th, 2009

I recently had a telephone conversation regarding documentation practices that planted a seed. I’m pretty sure this isn’t a new idea, how could it be, but it’s something that I’ve never seen explicitly stated.

I’m a big fan of static analysis and code metrics in general. The reason I’m a fan is that there’s something in my constitution that likes to see improvement over time. If I think a number correlates strongly enough with software quality, I’ll enjoy seeing that number improve. It’s soothing to me.

What I haven’t seen around is a metric that can be used to measure the quality of a software library’s documentation. Without such a metric, any investment in time towards improving its documentation will never be a sexy thing for me to work on, and I’m probably not alone in these feelings, since most projects have terrible documentation.

I think the # 1 most important thing to measure about a library’s documentation is its web analytics.

Here’s my train of thought: Ultimately documentation is about connecting users to answers. If your page is a promising candidate for solving their problem, then it should receive more quality visits. Anything you do that increases the number and/or quality of those visits is a step in the right direction. If you attempt to game the search engines, it would negatively affect the quantity of hits you’re documentation gets since search engines already take these kinds of things into account.

I’m not exactly sure how the metric will be computed but I’m absolutely sure it’d involve hits, duration of visits and bounce back rate.

I’m imagining a 3rd party documentation analytics embed code that can be used freely on open source projects and that can display on each documentation page a measurement of its “quality” and how its trended over time. It’d allow you to compare two equivalent projects’ documentation, and more importantly tell how much effort is being spent on a projects documentation.

Wouldn’t that be nice? So many open questions. What do you think?

Programming , ,

Original Composition – Glass of Water

December 6th, 2009

I don’t usually explicitly write country tunes because I find them silly. In this case, it fit the purpose exactly. :)

So, here’s my critique of Alternative Medicine in song format.

I hope you like it. :)

http://www.machete.ca/wp-content/uploads/2009/12/Glass%20of%20Water.mp3

Creative Commons License
Glass of Water by Allain Lalonde is licensed under a Creative Commons Attribution-Noncommercial 2.5 Canada License.

Music, Songwriting

Week 5 – Original – My My

December 4th, 2009

This is last installment of my song lyric odyssey. I had trouble picking a song as my last one so didn’t.

Instead, as I hoped it would, all this playing has made me itch to write again. So this week’s song is an original called “My My”. I wrote it Tuesday (the 2nd) and recorded it yesterday. I purposely built a chord progressions that at first sounds bizarre and then worked in a melody above it to bring it back in (I hope).

I hope you like it http://www.machete.ca/wp-content/uploads/2009/12/My My.mp3.

Music, Personal, Songwriting , ,