Posted in 'General' by James on October 31st, 2009
The news that David Nutt, the Government’s chief drug advisor was sacked, has not been taken lightly by the public. At least, this is the impression I’ve taken away from various publications. His role was to inform and advise the Government on drug related issues, such as the classification of certain illegal drugs and regulations surrounding their usage.
It is a pity that David got sacked, but from watching his reaction it looks like he’s much more annoyed at the principle behind the decision than the decision itself. The principle of course being that, when scientific evidence does not fall inline with current government policies, the government does what it can to suppress the scientific evidence.
In a letter to David, Alan Johnson, our home secretary wrote, “I cannot have public confusion between scientific advice and policy” (see BBC article). So, there it is, scientific advice does not fall inline with government policy, and as a result, the advisor got sacked!
I think this speaks quantities about the values and motives of our government, and generally of the democratic model and the effects it can have on the importance of truth.
The fact is, democracy lies in the favour of the majority, hence the ‘Majority rule‘. And it’s been proven countless times, that the majority are not always entirely correct in judgement!
Democracy is quite a curious thing really; in a perfect world it would work perfectly (duh!), although in a perfect world I doubt we’d need government anyway.
So, where we currently stand, some ill-informed, easily-malleable 18 year olds are allowed to vote, and not only are they allowed; their votes each have exactly the same value (to the government) as an OAP’s vote.
Who do you think is more qualified to make decisions in regard to this country’s future, the average 18-year-old, or the average OAP? I think, if we do not agree that OAPs are more qualified then you may as well just stop reading; we’re obviously not on the same page! What I’m saying is that, while it’s our future, I don’t think that we know enough about anything to make that decision (with confidence).
So, wouldn’t it be better if the value of your vote was proportionate to your age? Generally speaking, most things being equal, a person’s experience and knowledge of the world increases inline with age. So, I’ll ask again, why is it that my vote is just as powerful as each of my parents’ votes? Oh, because of democracy!? That model that we’ve coined as ‘the ideal’, nobody doubts it…
Posted in 'JavaScript' by James on October 31st, 2009
For those of you who are looking to take that next step in your steady uptake of the jQuery library, I can absolutely recommend Cody Lindley’s latest creation, “jQuery enlightenment“! It’s a breath of fresh air to be honest! It’s an overview of the jQuery library containing code samples (all available through JSBin.com), notes from the author and many applicable techniques.
- Core jQuery – all the foundation stuff is covered in this chapter, but Cody doesn’t hold back – he explains everything in considerable detail.
- Selecting – the various ways to select elements are outlined here, plus a couple of common problems are addressed, such as “selecting elements by searching attribute values using regular expressions”.
- Traversing – an overview of some of the available DOM traversal methods.
- Manipulation – covers the basics of element manipulation.
- HTML Forms – quite an exhaustive chapter that details the techniques used to work with forms in jQuery.
- Events – an overview of how jQuery manages events plus some applicable examples.
- jQuery and the web browser – A couple of useful snippets.
- Plugins – how to create them, best practices, useful advice.
- Performance best practices – Some useful advice for the performance conscious developer.
- Effets – An introduction to jQuery’s animation capabilities, plus a couple of helpful tips regarding its usage.
- Ajax – A brief overview of jQuery’s XHR capabilities (plus JSONP)
- Miscellaneous concepts – Useful advice that doesn’t quite fit into any of the above chapters.
Beginners and intermediate level jQuery coders will benefit from this book. Even if you’re ‘advanced’ you might pick up a couple of things. Purchasing a PDF copy is only $15, which seems a reasonable price to me, plus a portion of that goes directly to the jQuery project itself!
From the introduction:
jQuery Enlightenment was written to express, in short-order, the concepts essential to intermediate and advanced jQuery development. Its purpose is to instill in you, the reader, practices that jQuery developers take as common knowledge. Each chapter contains concepts essential to becoming a seasoned jQuery developer.
Pick up a copy!
Posted in 'JavaScript, My Life' by James on October 29th, 2009
For those of you that don’t know, I’m currently studying Computer Science at the University Of Kent. As our first programming assignment we had to create a game of Pong (see screenshots here) using Java and a 2D-graphics platform called Greenfoot. It was a challenging and interesting assignment, within which I was able to discover many new things about Java and about general game development.
In my opinion, Java’s insistence on a class based approach makes it a fantastic programming language to start with, albeit being quite hefty, in terms of the sheer quantity of available classes. I also liked the fact that most of my knowledge of JavaScript could be applied to Java. There are a few syntactical discrepancies that left me confused, but all the foundation concepts were (more or less) the same.
I thought it’d be fun to port my Pong game over to JavaScript. It was painlessly quick to do actually, and it’s the first time I’ve ever built a game with JavaScript and the HTML5 canvas tag/API. You can head over to the demo to play it for yourself, and feel free to have a look at the source code. It’s not quite as sophisticated as the Java one, I didn’t have time to add cool graphics or a scoring mechanism. And yes, I know it’s the wrong way round – we were told to do it that way!
What I discovered
It’s a frame-by-frame thing
One of my very first revelations was that, to create a game, it’s important to think about everything on a frame-by-frame basis. Every new frame is a fresh slate upon which you reflect the various states represented in your program. The relationship between any two frames depends on a persisting programmable interface that “remembers” previous states.
It all becomes wonderfully simply when you think about it in this way… move the ball one cell to the left, if its position is equal to zero then it must be at the left wall, therefore we can bounce it off the wall! (okay, so it’s not actually that simple – you have to take the ball’s width into account)
It’s a massive contrast from ‘event-driven’ development, wherein you wait for the user to make a choice and then carry out something following that. In the Pong game, I’m not waiting for the user to do anything – on every new frame I simply query the necessary information to make stuff happen. For example, If the left cursor key is currently down then move this (paddle) one cell to the left! (I’m not waiting for the user to press the left cursor key, each frame is being drawn regardless.)
Everything’s an object
In my Pong game, each physical object in the game is represented as an object within the programmable layer, each one an instance of a predefined class. For example, there’d be one Paddle class from which two Paddle instances (“objects”) would be created, each representing a single physical paddle on the screen.
OOP really shines here!
Abstract, but not too much!
Abstraction really is very important, especially when there are tonnes of things that need to be happening at any time. What I actually mean here, is that it’s important to separate out functionality between your methods. This is obviously better:
Posted in 'JavaScript' by James on October 17th, 2009
The following quote is derived from an expert recommended book that covers the many aspects of Ajax. It’s called “Ajax in Action”, authored by Dave Crane, Eric Pascarello, and Darren James.
“The JavaScript Object Notation (JSON) is a core feature of the language [JavaScript]. It provides a concise mechanism for creating arrays and object graphs. In order to understand JSON, we need to know how JavaScript arrays work [...]”
Hopefully you’ve spotted the dodgy parts of that quote. For one, JSON, the data-interchange format is not actually a core feature of JavaScript and is, in more ways that one, quite different to JavaScript’s object notation (i.e. the way you markup an object literal in JavaScript code).
Despite my dismay I continued to read onwards, and I can tell you that the author has also made the classic mistake of thinking that JavaScript supports associative arrays, and for some reason thinks that you have to understand JavaScript arrays in order to understand JSON… (???)
So, just to set the record straight, JSON is an interchange format created/coined by Doug Crockford. It’s a subset of JavaScript’s object notation (specified in the ECMA-262 specification). To prove this, here’s a valid JavaScript object literal:
Yes, I know, on its own it’s not valid JavaScript (since it’s interpreted as a compound statement), but that doesn’t matter; it is a valid object literal.
Run that through a JSON validator and you’ll get errors. That’s because JSON is not the same as JavaScript’s object notation. To make the above code a valid piece of JSON you’d have to wrap each property name (e.g. foo) with double quotes:
{
"foo": 123,
"bar": 456
}
I don’t blame the author of that book. In all likelihood, the information within that book was thought of as 100% correct at the time of writing. I only wanted to set-straight one of many misconceptions surrounding JavaScript and its “subsets”.
PS. Please forgive the confusing title.
Posted in 'Code Snippets, JavaScript' by James on September 11th, 2009
A while ago I posted a method I had been using at the time to remove comments from JavaScript code. It was pretty decent – instead of using a regular expression it steps through each character and removes comments where it finds them.
At the time I thought stepping through a string character-by-character was the only reliable way to solve the “comments problem” but after giving it another attempt I found that it was possible with a only a few regular expressions and a fairly moderate dose of JavaScript’s replace() function.
Here it is:
function removeComments(str) {
var uid = '_' + +new Date(),
primatives = [],
primIndex = 0;
return (
str
/* Remove strings */
.replace(/(['"])(\\\1|.)+?\1/g, function(match){
primatives[primIndex] = match;
return (uid + '') + primIndex++;
})
/* Remove Regexes */
.replace(/([^\/])(\/(?!\*|\/)(\\\/|.)+?\/[gim]{0,3})/g, function(match, $1, $2){
primatives[primIndex] = $2;
return $1 + (uid + '') + primIndex++;
})
/*
- Remove single-line comments that contain would-be multi-line delimiters
E.g. // Comment /* < --
- Remove multi-line comments that contain would be single-line delimiters
E.g. /* // <--
*/
.replace(/\/\/.*?\/?\*.+?(?=\n|\r|$)|\/\*[\s\S]*?\/\/[\s\S]*?\*\//g, '')
/*
Remove single and multi-line comments,
no consideration of inner-contents
*/
.replace(/\/\/.+?(?=\n|\r|$)|\/\*[\s\S]+?\*\//g, '')
/*
Remove multi-line comments that have a replaced ending (string/regex)
Greedy, so no inner strings/regexes will stop it.
*/
.replace(RegExp('\\/\\*[\\s\\S]+' + uid + '\\d+', 'g'), '')
/* Bring back strings & regexes */
.replace(RegExp(uid + '(\\d+)', 'g'), function(match, n){
return primatives[n];
})
);
}
Theoretically this should work perfectly in almost all situations. Don’t bother even trying it with E4X as that definitely won’t work! E.g.
var someE4X = <box>// this is NOT a comment</box>;
It's impossible to cater to E4X with regular expressions because XML is a recursive structure. I'm not bothered though as E4X isn't exactly a widely used extension. It also doesn't play well with conditional compilation but frankly, conditional compilation shouldn't exist anyway.
Anyway, back to the solution. It takes a pretty conventional approach of removing all strings and regular expressions first and then moving on to the comments. Unfortunately comments are not as simple as \/\*.+?\*\/ - there are nested comments within strings, nested comments within literal-regular-expressions and nested comments within other comments.
Posted in 'JavaScript' by James on September 10th, 2009
I better do some explaining after that unnecessarily provocative title… jQuery is obviously a fantastic JavaScript library and has been my tool of choice for quite a while now, and it’ll probably continue that way until something better comes along. What I wanted to discuss today though has nothing to do with the technical aspect of jQuery but rather the plugin culture that’s formed around it and some of the possibly negative effects of this culture.
The problem I’m about to outline may be inherent of other plugin cultures within other libraries too but I won’t dare mention them at the risk of starting a flame war. This isn’t really about jQuery, this is about a much larger problem which has proven to be unavoidable and unstoppable on a platform as pervasive as the internet.
So here’s the problem: Joe Average needs some “cool JavaScript stuffs” to impress his client – he hops over to the plugin repository (more likely, Google) and searches for some specific jQuery plugins. After choosing the plugins he desires he will delegate to each one a certain chunk of responsibility – the cycle plugin gets the featured-banner, the validation plugin gets all the forms, and the tooltip plugin gets the navigation menu, and the list goes on. By the end, Joe has 5 plugins he wants to use on his newly developed website. So, like any innocent developer he sticks them all in the <head> and calls it a job well done!
There are over 3000 plugins in the jQuery plugin repository and probably multiples of that amount floating around elsewhere. With so much functionality at the tip of our fingers it’s no wonder that most of us have succumbed to the notorious copy-and-pasting-syndrome.
The jQuery plugin culture is essentially just an extension of this. Sure, many of the plugins are much more reliable than any random code snippet but it’s still the same. I think this “syndrome” protrudes most significantly into jQuery because of its popularity amongst people that have no interest in JavaScript whatsoever… I’m talking about the thousands of designers and interface-engineers who use jQuery on a daily basis yet have no interest and very little knowledge when it comes to JavaScript and its various abstractions. To these people it seems okay to bombard users with a symphony of jQuery-chaos at the expense of many-hundreds of kilobytes of mostly-useless JavaScript code.
The most popular jQuery plugins have been made to suit many different situations. Let’s take the “cycle” plugin by Mike Alsup as an example – it’s a very well built plugin that is very easy to integrate and even simpler to customise. The one problem with it though, and this is inherent of all the most popular plugins, is that it tries to cater to every conceivable usage at once. This results in 20kb (at minimum) of mostly unused code. Most users of this plugin will probably use only one or two of its features on any particular website. If they were to write the desired functionality from scratch than I doubt it would take up any more than 2kb. I may be over-simplifying and making many assumptions but it’s an undeniable fact – there is a problem with this plugin-model. As it currently stands, the model offers only a marginal benefit to the user… suddenly, it’s all about the developer!
There’s an obvious cost – if building the functionality from scratch results in only 2kb yet using the plugin is a monstrous 20kb then the cost of using the plugin is 18kb. We don’t feel the brunt of it though – it’s our users that suffer. Note that I’m not talking about the monetary cost (as a business would see it); and this really shouldn’t be considered at all – when it comes to doing the right thing, money is no object!
There are obvious exceptions to the outlined problem though; not all plugins try to do everything at once and not all plugins are that huge but the crux persists: these plugins are used as if they were throw-away snippets, integrated on a whim by some designer that thinks “jQuery rulez!”
This is probably contrary to the concept of code-reuse but this is what I tend to do: If I need a piece of functionality and if I know how it’s achieved then I’ll build it myself. Some may think it foolish to constantly re-invent the wheel but I would have to disagree – doing this allows you to progress as a flexible developer – one who can confront many different problems without having to rely on multiple abstractions.
There are times when I’ll gladly use someone else’s code but it’s normally only when that code caters to a very specific problem that is quite unique and difficult to solve. For example, I use the history plugin a lot! It does just one thing and it does it very well!
jQuery itself is a massive abstraction and has closed the gap between those-who-can’t and those-who-can. Do you really need any more? I’m not saying you should stop creating and using plugins, I’m simply saying that the usage of any particular plugin needs to be carefully considered! Remember, it’s not about you, it’s about the users!
Posted in 'Code Snippets, JavaScript' by James on August 31st, 2009
Here’s a nifty little trick that allows you to write “contextual” JavaScript. It’s incredibly obtrusive and probably shouldn’t be used at all but it’s still a pretty cool idea:
<div id="some-div">
<script type=":contextual">
alert(this.id); // "some-div" is alerted
</script>
</div>
Instead of the this keyword referencing the global object (window) we can make it reference the parentNode of the script element. Here’s the code that makes it work:
(function(){
var scripts = document.getElementsByTagName('script'),
script, i = 0;
while ( (script = scripts[i++]) ) {
if ( /:contextual$/.test(script.type) ) {
(new Function(script.innerHTML)).call(script.parentNode);
}
}
})();
Take it or leave it! – I’m indifferent either way – yes, it’s obtrusive but you’ve got to admit, contextual JavaScript looks pretty neat!
Posted in 'Code Snippets, JavaScript' by James on August 20th, 2009
Satisfy is a development-only jQuery plugin* that you can use to quickly generate HTML for testing/debugging. The idea is that you provide a CSS selector and then the plugin will “satisfy” it by generating an HTML structure in accordance with that selector.
* – UPDATE: This is no longer just a jQuery plugin – as of version 0.2 Satisfy has no dependencies. See the comments for more info.
For example:
jQuery('div a').satisfy();
… would return the following HTML structure:
A more snazzy example:
jQuery('ul li:5 span[innerHTML="link"]').satisfy();
… which would return the following:
<ul>
<li><span>link</span></li>
<li><span>link</span></li>
<li><span>link</span></li>
<li><span>link</span></li>
<li><span>link</span></li>
</ul>
(Note: It ignores combinators (+|~|>) and pseudo-classes (:pseudo). It adds support for numerical pseudo-classes (e.g. “:5″) which you can use to specify how many of a particular element you want.)
More information and source available at Github – “satisfy” @ GitHub
Posted in 'JavaScript' by James on August 19th, 2009
I can’t speak for other languages but one of the best things about JavaScript, in my opinion, is the fact that almost everything can be considered as an expression. An expression makes up part of a “statement” and is evaluated to produce a value. Every expression has a “return” value. Consider this:
Yup, the number 42 happens to be an expression. This expression is evaluated as the literal number, 42. You can create more complex expressions by using operators. An operator (e.g. the assignment operator, =) expects a number of “operands”.
An “operand” can be thought of as an operator’s argument. For example, what we all know as the “ternary operator” (x?y:z – actually called the “conditional operator”) takes three operands, hence the name “ternary”. It’s the only operator in JavaScript that takes three operands. The assignment operator (=), for example, takes two operands – one on the left and one on the right.
Operators and their corresponding operands can be combined to create interesting and useful expressions. Expressions, as the name suggests, allow you to “express” a piece of logic concisely and efficiently. Much of the logic expressible in a series of if/else statements can also be expressed in a tiny expression.
Precedence & Associativity
Consider the following expression:
There are two operators; the unary plus operator (+) and the new operator. What would you expect this expression to do? Would you expect the + operator to convert the new operator to its numerical form? Would you expect a syntax error to be thrown? Nope? Then what?
The + operator actually “waits” until the new operator resolves its operand; then the + acts on the returned object. So, +new Date() is fundamentally the same as +(new Date()). The order in which operators run is defined by each operator’s “precedence”. The new operator has a higher precedence than the unary plus operator so it’s evaluated first.
Here’s another example:
The logical OR operator (||) expects two operands, one on the right and one on the left – if the one on the left evaluates to true then it’s returned (z never gets a chance to evaluate). If, however, the one on the left is false then the one on the right is evaluated and returned from the expression. The return value of y || z is assigned to x – this is what you’d expect – but underneath the surface it’s the precedence of each operator in the expresson that defines what happens.
Posted in 'JavaScript' by James on August 17th, 2009
I’ve seen a lot of curious (bordering on horrific) code in my life; and I’d say about half of it was written by me. If you don’t attest to the fact that you once wrote crap code then you’re either a liar or perhaps, have omnipotent powers!
Here’s a relatively small collection of what I see as bad JavaScript practices; in other words – a list of how to write really really ugly JavaScript that will break! I know it’s quite a negative angle to take but it’s easier than writing a post on best practices, plus it gives me a chance to vent! Many of these are things I’ve done in the past; I’ve since discovered the errors in my ways.
Non-constructor identifiers beginning with a capital letter
Variable names should only begin with a capital if they’re pointing to constructor functions. Doug Crockford has more:
There is a convention that all constructor functions are named with an initial capital, and that nothing else is spelled with an initial capital. This gives us a prayer that visual inspection can find a missing new.
Not following conventions will only get you in trouble! So, to be clear, this is all wrong:
var Color = 'red';
var SomeNumber = 234;
var AnArray = [1,2,3];
var Foo = { bar: 123 };
// None of them should start with a capital letter!
Only functions that are constructors should be identified with an initial captial letter, not regular functions. E.g.
/* This is a regular function. */
function sum() {
var total = 0, i = 0, len = arguments.length;
for ( ; i < len; ++i ) {
total += arguments[i];
}
return total;
}
/* This is a constructor function */
function Widget(innerText, styles) {
this.innerText = innerText;
this.cssStyles = styles;
}
Not using the var statement to define variables
Not using the var statement when defining variables for the first time is a very bad idea. These variables will become part of the global scope. This sucks because you won’t get any warning. Not only is it a bad practice but it can have a negative affect on performance, after-all, the further away a scope is the longer it takes to access. So, always use the var statement:
foo = 3; // NO!
var foo = 3; // YES
Prefixing every new variable in a given scope with var
There's no point in having several var statements if you only need one:
var someVar1 = 'a';
var someVar2 = 'b';
var someVar3 = 'c';
// Much easier:
var someVar1 = 'a',
someVar2 = 'b',
someVar3 = 'c';
Using non-strict comparison operators, and then comparing across different types
There are two classes of comparison operators; those that type-cast (==/!=) when required and those that don't (===/!==). You don't ever want to use the former!
1 == "1"; // true
false == " \n\t "; // true
[[],[]] == true; // true
// ... Confused?
See? It's obviously a bad idea! Please only ever use strict-equality comparison operators; they'll check that the two operands are identical, not just "equal":
1 === "1"; // false
false === " \n\t "; // false
[[],[]] === true; // false
// Just as expected!
Not "caching" non-varying complex objects
This is vitally important; if you're going to be repeatedly using an object you should name it and save it! A basic example: