The Miscellanean

Break Logic into Modules

So one of the things I dislike about all the Express examples I’ve seen (this is admittedly a limited set and I don’t mean it as an indictment of the library so much as an indication of my ignorance) is that the logic exists all in one file.

There’s a blog example that comes with the latest version of Express that breaks the logic into multiple files, but even that isn’t really a class-like system. It just shows how you can transfer logic into any “app” (using the term in the django sense where many small apps come together to be a large app) but even the sample sub-app keeps all its logic in one file.

The node-boilerplate project designates a spot inside app.js where all routes should be specified. But building on the simple logic demonstrated with the Express sample apps would suggest that all the controller and model logic should sit inside anonymous functions right there in app.js.

It’s not like anything I’m building is especially elaborate, but still that kind of makes me shudder a bit. What little logic I already have at this point (and it really is a little) is still 20 or so lines and that’s just the very barest of a start.

Node.js uses the CommonJS Module Standard. The link goes to the 1.0 spec, but there are indications that it is getting slightly out of date. I don’t know just yet which version Node.js conforms to.

With quite a lot more detail, the CommonJS Module Standard describes the use of the function require( moduleIdentifier ) function to include a module and the exports object used within a module to export functions.

It’s a nice and simple system. I’m about to go and migrate the small amount of behaviour written for the Doris project into modules and try to pass logic from the routes section to the modules, sort of in a Model View Controller pattern. Although I’m not sure where the Model fits in just yet; probably just as its own module.

Upgrading node.js

Last night I was poking around breaking my current node.js project into smaller pieces. I was irritated by the lack of a solid project structure in any examples or articles that I could find, so I decided to start my own, probably get it wrong, and be mocked and abused into correctness.

I wanted to incorporate HTML5 Boilerplate because I really think it’s a cool project. I got about an hour into it, making only a small amount of progress (I’ve been catching up on Dr. Who during my experimentation time and unlike many series find it much more difficult to actually get work done).

This morning I was pleasantly surprised when I saw today’s today’s DailyJS which contains a link to node-boilerplate. The best kind of open source project is the one that is exactly what you wish you’d gotten done, and this case it is all a big win for me.

So tonight I cloned the project and, following the very easy instructions, started a new one to import the Doris work already completed. When attempting to run the default project I received an error message that contained in part the message:

TypeError: Object # has no method 'on'

A brief bit of poking revealed that there’s only one issue in the node-boilerplate project, which feels like a similar problem and the first response is a recommendation to upgrade node.js so I thought that would be a good idea to try.

When I originally installed node.js, I cloned the project from git and built it from source. Easy peasy, so I just did the same thing. Much to my chagrin, executing node -v revealed the same version (v0.1.98-31-g1c6671a) as previously. Even deleting the binary in the path and changing to the build directory and running ./node -v to ensure the freshest build was used resulted in the old version number. Frustration!

I fumble around command lines like a bull in a china shop, but this time managed to make it out with the shelves intact.

From somewhere in the dregs of my brain I remembered make install clean which tidies up all the side-effects of make. I ran it, then re-configured and built the source and aha! node -v reports v0.1.104, running the sample node-boilerplate app works successfully.

As a very happy bonus, the basic boilerplate project is an example of using Socket.IO which uses websockets and other client/server transports which is something this project will benefit from.

Long Conditional Styling

I care, probably a little too much, about the aesthetics of code and sometimes would happily polish polish polish without adding any actual improvements. I consider this in part a flaw since it does impact my productivity but I also justify it by including it under the umbrella of ‘coding as craft’. A little bit.

Anyway, something that has been bugging me for a long time is large conditionals. I do think that line length matters, and though I’m not a strict 80-characters kind of guy (not strict) I do tend to think that the depth of the code is a bit of smell.

So an example of a large conditional is something like:

if( someCondition && ( someObject.property && anotherObject.longFunctionNameBecauseIBabble( 'stringParameter', intParam ) ) ) { // do stuff.... }

For a while I’ve been trying to settle on a pleasing-to-me way of cleaning that up and only just finally realized something that had been staring me in the face for a long time (and I’m pretty sure is addressed in Code Complete). I’ve typically tried resolving it by adding line breaks:

if( someCondition && ( someObject.property && anotherObject.longFunctionNameBecauseIBabble( 'stringParameter', intParam ) ) ) { // do stuff... }

But there are two problems with that structure for me. One is what to do with the opening brace and another is the loss of indenting value.

The reason to indent code is to ease readability. You can identify what is being executed on a particular branch by virtue of it being aligned. I think I care a little more about indenting every year as I dabble more and more in python, but even in whitespace-agnostic languages there’s a lot of value in good indenting (that is belabouring something that is probably taken for granted by this point, but I’m nothing if not belabouring).

In the above (and below, actually) examples the value of indenting is lost because the conditions are indented to the same point as the code and it becomes more difficult for me to parse what is condition and what is executed.

The brace thing is even more trivial, but slightly related to the indenting question. Should I indent the close paren of the conditional to the normal tabstop, or to the character location of the open paren?

And if I place the close paren and the opening brace of the block as I did in the above example on its own line then indenting rules are generally followed, but if I put it on the same line as the last condition then the indenting becomes slightly more useful again because there’s more content on the line above the executed code which makes the whitespace more obvious:

if( someCondition && ( someObject.property && anotherObject.longFunctionNameBecauseIBabble( 'stringParameter', intParam ) ) ) { // do stuff... }

The final answer is one that is well-known, but for some reason I’ve resisted it. By storing the condition in a variable every thing becomes clearer:

success = someCondition && ( someObject.property && anotherObject.longFunctionNameBecauseIBabble( 'stringParameter', intParam ) ); if( success ) { // do stuff... }

A conditional like the above is heavily exaggerated, and honestly I probably wouldn’t indent the function parameters but I’ve exaggerated it to highlight how much nicer this looks to me. The value of success is determined and then used.

I’m not entirely sure why I’ve resisted it. Almost certainly a stale and foolish concern about using too many variables which is entirely misplaced when writing on top of an already moderately high level language and framework anyway, as I usually am. It is time to dispose of that concern which probably was never valid anyway.

On Understanding JavaScript

So for the past few months I’ve narrowed down the projects that I’ve allowed myself to work on to two. Which probably isn’t really narrowing down enough, but one of the things I’m learning about myself is that a series of small steps with a specific outcome is an effective way of progressing.

Both these projects – Fracas, which I’ve mentioned here and a currently nameless one (I grew tired of the previous name and am not entirely pleased with the working name) which I have yet to but is all over my personal blog archives – are quite heavily reliant on JavaScript.

I am coming to the realization that JavaScript is my language of choice for the next phase of my career. I have tried writing this paragraph half a dozen times now and that seems to be the best phrasing of the statement I am trying to make. I think JavaScript is coming into its own and will be an extremely important language in the coming decade, but mostly I’m just into it in a way that I have felt the absence of in languages thus far. I want to do more than just program with it, I want to understand it.

I’ve been using JavaScript, with varying degrees of regularity since about 1998, but while working on Fracas and the unnamed project I’ve been extremely frustrated about my lack of understanding of modern JavaScript syntax and how it works and how libraries and tools built in JavaScript (specifically jQuery but also other projects like Node.js) work.

I finally over the past little bit decided to really start doing something about it and finally, after all these years, managed to stumble onto Douglas Crockford. Technically I should have known his name long ago since he is the inventor of JSON but I guess I’ve just read the specification itself a dozen times without paying attention to how it became one.

Anyway, Mr. Crockford knows his JavaScript and he knows how to explain it. Last night I read Code Conventions for the JavaScript Programming Language and immediately understood several important details that had been confounding me to no end. Crockford recently presented a 5-part lecture series on JavaScript that is a great watch.

What follows is an extremely heavily edited version of jQuery, with the vast majority of its guts ripped out leaving only a few bits and pieces to illustrate the places I was getting confused. If you were to paste it into script tags it would cause errors since jQuery.each is not defined, so it’s not actually executable just for looking at.

(function( window, undefined ) { // Define a local copy of jQuery var jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context ); }, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // ... snipped a bunch... indexOf = Array.prototype.indexOf; jQuery.fn = jQuery.prototype = { init: function( selector, context ) { var match, elem, ret, doc; // ... snipped a bunch ... }, // Start with an empty selector selector: "", // ... snipped a bunch ... sort: [].sort, splice: [].splice }; // ... snipped a WHOLE bunch ... // Create innerHeight, innerWidth, outerHeight and outerWidth methods jQuery.each([ "Height", "Width" ], function( i, name ) { // ... snipped a bunch ... }); // Expose jQuery to the global object window.jQuery = window.$ = jQuery; })(window);

This framework, within which all of jQuery is defined, just baffled the shit out of me primarily due to lack of understanding of conventions.

Parentheses in JavaScript, like most C-style languages, are used as part of control structures and function declarations are vital there. But they’re also a completely trivial part of normal statements used for clarity – like when grouping parts of a mathematical statement as in (1 + 2) + (3 + 4). So in this jQuery code the whole thing is wrapped in parentheses, followed by another pair of parentheses containing ‘window’:

(function( window, undefined ) { })(window);

That second pair of parentheses I understood, it called the anonymous function immediately passing it window as a parameter but why that first pair? Well, Mr. Crockford clears it up for me:

When a function is to be invoked immediately, the entire invocation expression should be wrapped in parens so that it is clear that the value being produced is the result of the function and not the function itself.

Oh. Cool!

I have a couple of guesses why window and undefined are being passed. The former probably ensures that the global window object is what’s actually being used inside of jQuery, and the latter seems like a convenient way to create something to use to test if variables have been defined. But this whole paragraph is speculation, I’m really not entirely sure about it just yet.

The next convention I was unaware of is illustrated by this block:

// Define a local copy of jQuery var jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context ); }, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // ... snipped a bunch... indexOf = Array.prototype.indexOf;

It’s more easily illustrated later in the source with the line:

var match, elem, ret, doc;

It’s a simple convention, common in most languages, and is simply the declaration of multiple locally-scoped variables. For some reason I was conflating the use in jQuery (and other scripts I’ve seen in recent months) with an object literal, likely because I am only just on the cusp of understanding them, too. I’m getting there though.

Only two more things, which is quite a bit for a small block of code. The first of which is interesting to me because it’s completely novel to me and fairly illustrative of why JavaScript fascinates me so much.

var jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context ); } // ... snip snip snip jQuery.fn = jQuery.prototype = { init: function( selector, context ) { var match, elem, ret, doc; }, // ... snip snip snip };

So, an object named jQuery is created. The way JavaScript works is that the object declaration is also its constructor (my terminology is likely weak, I would love to be corrected), so in this case the only thing that the object is is a call to a member function that doesn’t yet exist. Shortly afterwards, it’s defined.

Why jQuery uses jQuery.fn for instead of jQuery.prototype I haven’t yet got around to understanding but they do. The second bit above assigns an object literal to the prototype which contains the actual init function. Again, I’m not entirely sure why this particular behaviour is used (is it convention or to work around an issue or maybe it’s just Resig’s style?) and look forward to that next level of comprehension.

// Create innerHeight, innerWidth, outerHeight and outerWidth methods jQuery.each([ "Height", "Width" ], function( i, name ) { // ... snipped a bunch ... });

So this last bit, the part that will throw errors, is only to point out how little it takes to lose me. See, the end of this statement (});) comes right at the end of the file, some 6200 lines after the start. It’s also a sequence of characters that is usually used at the end of an anonymous function passed as a parameter to another function (callingFunction( function(){/*stuff*/});) and since I’d assumed that all of jQuery was defined as an anonymous function (no, I don’t know why I’d assumed that, outside of the same lack of understanding as all along) which was easy to clear up in the end but combined with everything else I wasn’t getting caused a couple of small bumps in comprehension.

I’m at the point where I’m starting to get the how, at a slightly deeper level than before, but I’m still only just scratching the surface of the why.

A Testing Fixture

The next major block of work I want to do with Fracas isn’t specific to gameQuery. Fracas is a simple combat engine, so I need to create some things that do combat. To that end, I’ve created a base class called Character, of which there will be two major subclasses PlayerCharacter and NonPlayerCharacter.

Each combat setup will feature multiples of each. A player’s party will consist of four instances of PlayerCharacter, who will be doing combat against some number of instances of NonPlayerCharacter. Combat is managed primarily by these instances passing around instances of the Attack class.

An instance of Attack is created by an instance of Character and contains what are effectively the to-hit roll and potential damage roll. How those are generated are details I will go into another day. The defending character accepts the Attack instance and processes it. If they dodge or parry the attack no damage is inflicted otherwise the potential damage is realized.

This interaction is the core gameplay and therefore needs to be tested fairly well both for functionality and to ensure a healthy balance. For me, testing JavaScript has primarily involved all sorts of page reloads which I find really annoying, for reasons I can’t really identify. I just don’t like my current JavaScript cycle and have been thinking of something new.

Enter jQuery’s jQuery.getScript() function. This allows me to arbitrarily load new code, so what I am playing with right now is a Fixture class in a separate file. In its very initial state it looks like this:

Fixture = function() { var foo = 1; var bar = 2; return { init : function() { console.log( 'foo:' + foo ); } } }

Then what I can do from the console is execute the following commands:

jQuery.getScript('http://localhost/fracas/lib/fixture.js'); var fixture = new Fixture(); fixture.init();

And the log reads: foo: 1

Where it becomes a little bit interesting, to me at least, is that I can edit the file directly, say changing the console.log line to: console.log( 'foo:' + bar ); and when I execute the exact same three lines, the log now reads: foo: 2

I’ve been thinking of this flow for a couple of days, but only just got this far. I’m pretty sure this is going to change how I develop JavaScript. At the very least I’m suddenly more interested in having destructors and I have absolutely no idea how such a thing might work in JavaScript.

In the short term, I expect to be able to reload the Fixture and setup a bunch of characters and play at attacking between them without having to reload the page every time. I, uh, I’m not actually sure that gains me anything, but it sure seems like it will be fun.

gameQuery Groups

gameQuery uses a concept called groups, which are pretty a pretty typical layer sort of thing. The analogy I like the best is acetate sheets, placed atop one another. Groups are containers for other game objects, which at these point in my understanding of the library (very limited) appear to be predominantly Sprites and Animations.

For Fracas I don’t really know what sorts of groups I’m going to need, but as a starting point I’m going to add three. Not a group, but useful and sort of relevant, is the background image for the playground. Initially I’m starting with a super ugly placeholder image that displays the two sections of the interface, an 11×11 tile grid where all the action takes place, and an information area that will contain character information, messages, and whatnot.

The three actual groups will be one for the map tiles, one for the character and NPC sprites, and one for any overlays or effects or such. I’m not sure yet that I’ll be doing anything with that one but it seems like it will be fun.

The script shown in the previous post has a fairly massive playground initialization that does add a group. I’m going to enhance that a bit, change the existing group (which was called ‘background’ and isn’ really necessary) and add two more. As a starting point, I’m just adding them straight in, so that big bulky block gets changed from:

var playground = $('div').attr( 'id', 'playground' ) .css( 'height', pgOptions.height + 'px' ) .css( 'width', pgOptions.width + 'px' ) .css( 'border', '1px solid black' ) .css( 'background', 'url( images/background.png )' ) .playground( pgOptions ) .addGroup("background", pgOptions);

To:

var playground = $('div').attr( 'id', 'playground' ) .css( 'height', pgOptions.height + 'px' ) .css( 'width', pgOptions.width + 'px' ) .css( 'border', '1px solid black' ) .css( 'background', 'url( images/background.png )' ) .playground( pgOptions ) .addGroup("map", pgOptions).end() .addGroup("characters", pgOptions).end() .addGroup("overlay", pgOptions).end() ;

The end() function is a convenience function to allow continued fluid interface. It returns the previous selection, which in this case is the playground. addGroup() typically returns the group it creates but to manage a giant initialization structure like this one I just want to keep altering the playground which end() lets me do.

After the groups are created, everything needs to be added to the group, etc. Because of the fluid interface we could just prepare everything in advance of that giant line but I’m going to try moving the logic into a set of initialization functions, so the block now becomes:

initFracas = function() { var playground = $( '<div></div>' ).attr( 'id', 'playground' ) .css( 'height', pgOptions.height + 'px' ) .css( 'width', pgOptions.width + 'px' ) .css( 'border', '1px solid black' ) .css( 'background', 'url( images/background.png )' ); $('body').append( playground ); playground.playground( pgOptions ); initMap(); initCharacters(); initOverlay();

It’s also worth noting I changed a few things, and am being more explicit in the way I create the div. I’m not entirely sure how it was working in the last version, but after breaking things out into the init functions it stopped working because I wasn’t properly adding the newly created div to the body.

The details of the init functions, beyond just the previous addGroup() commands, is yet to come.

gameQuery Starter

I’ve been poking and prodding at a simple JavaScript turned-based combat system I call ‘Fracas’ for several years now, and when I first read about gameQuery I knew it was time to dust it off again.

I’ve very slowly gotten around to downloading the library and starting to figure it out. It’s pretty simple to get started but when reading the instructions and tutorials there wasn’t something that put it into steps simple enough for me to follow so as I dug around and figured it out from the demos I pretended to take notes for this write-up.

To get started, one needs a web page that references both jQuery and gameQuery. jQuery I prefer to just get from Google’s servers, and gameQuery I downloaded.

All the tutorials and examples and such start off with a div with the attribute id='playground' in the html but for me, I want the entire site to be rendered by JavaScript because, well, what the heck?

<!doctype html> <html> <head> <title>Fracas!</title> <script src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js'></script> <script src='lib/jquery.gamequery-0.4.0.js'></script> <script src='lib/fracas.js'></script> </head> <body> <div id='playground'></div> </body>

Inside fracas.js is where the game logic is eventually going to lie, but for now it just creates and styles div that contains the game then triggers the gameQuery setup with the playground function.

(function() { initFracas = function() { var pgOptions = { height: 480, width: 320, }; var playground = $('div').attr( 'id', 'playground' ) .css( 'height', pgOptions.height + 'px' ) .css( 'width', pgOptions.width + 'px' ) .css( 'border', '1px solid black' ) .playground( pgOptions ); } window.onload = function(){ initFracas(); } })();

The next step (and probably post) will be to setup the game screen, which should be only a few lines. The gameQuery tutorial moves on to animation at this point, but I’ll probably skip ahead to working on some game objects. I’m not sure just yet.

Colophon(ish)

I’ve officially abandoned the idea of writing my own blog engine (primarily out of disinterest) and for the past few days have been configuring WordPress. Until recently I haven’t had a great deal of direct experience with WordPress outside of a few posts here on a couple of long dormant sites created for one purpose or another.

A little while back I offered to help out with the DemoCamp Guelph website, which we recently switched to WordPress and I found the process pretty straightforward and the code generally quite easy to use. Having also recently rededicated myself to a development-oriented career path, my interest in a blog documenting my technical exploration was rekindled. A + B firmly in place, C was easy to find.

One of those long dormant sites was already installed here so it was easy to start. I began by exploring some themes, and ultimately rediscovered a bookmark I’d made some time ago to Manifest which I apparently found attractive then, and continue to find attractive now.

Manifest is simple, solid and other than a few small tweaks (mostly just to settle the nagging feeling that if I’m not going to make my own engine I should at least make my own theme) exactly what I want except for the lack of syntax highlighting for code.

For that I turned to Google’s Prettify a nifty little javascript and css combination that guesses the nature of a block of code and highlights it accordingly. I haven’t thrown anything complicated at it, but frankly good enough for Stack Overflow good enough for me.

The downside to Prettify is the way it wants to integrate with your site. It’s disappointing to me that any Google project recommends obtrusive javascript (especially since unlike say with Google Analytics I already need to reference an external file) but maybe that kool-aid I’m drinking isn’t necessarily Unarguable Truth flavour, so whatever.

But not entirely whatever, because there’s no reason I can’t initiate Prettify unobtrusively so that’s what I did. I created an additional js and css file with the justification that as the last included files I have a good shot of overriding anything I might not like about the template or anything else I may eventually add on.

It’s certainly nothing magical or impressive, but since I’m ostensibly here to talk about code, that’s what I’m going to do. Prettify requires that the code (or pre, but for semantic reasons I prefer to use code) element have the attribute ‘prettyprint’ for identification purposes.

code is an inline tag, like em or span it doesn’t break the flow of the surrounding text so one can, if they choose, discuss HTML tags without having to dedicate a new paragraph to the task. This makes styling a multi-line block a bit irritating since you can’t just apply say a border to the code block because then each line gets its own. Convention that I’ve seen and have used in the past is to wrap the code tag in a pre wrapper which by default displays as block.

Since I’m using JavaScript to trigger Prettify anyway I figure why not save me from writing a bit of HTML, and I came up with the following which properly sets the class for all code blocks, and wraps a pre tag around any code tag that is not an immediate child of a paragraph. That’s a moderately fragile limitation but I don’t expect to nest any blocks of code inside a paragraph.

Anyway, here’s the code, which also demonstrates one more tweak I’d like to make, which would automatically escape all the < and > symbols (done manually in this case):

$(document).ready(function() { $('code').each( function() { if( 'p' != $(this).parent().get(0).tagName ) { $(this).addClass( "prettyprint" ).wrap( '<pre />' ); } }); prettyPrint(); });

Second Post

This post is just filler while I poke around with the template.

Updated to include a code block to setup/test prettify.

class Voila { public: // Voila static const string VOILA = "Voila"; // will not interfere with embedded tags. }

Hi there.

My name is Rob Drimmie, I am the Miscellanean. I develop software for myself and for other people. This site is where I talk about that.