Posts Tagged code

Three Neat JavaScript Tips

JavaScript is a great language. It really can power your entire web stack from animated effects on the frontend to ajax calls for faster user experiences, to backend JSON APIs written in NodeJS. It’s been called the language of the web before, and never has it been more true than now.

I’d like to share some little techniques I’ve picked up which make your life easier as a professional JavaScript developer. Actually the first two are applicable to many languages.
Read the rest of this entry »

, , , , , ,

No Comments

Poking holes in PHP object privacy

Get it? Holes? Cheese?PHP provides a decent model of class member visibility, with public, private, and protected members to help you define tight APIs for your objects and show other developers how your object is supposed to be used. But used naively, PHP’s ‘magic methods’ can easily and subtly subvert this system, making everything public.

If you’re still new to object oriented programming in PHP5, think of “public” as roughly analogous to “my function’s arguments” and “private” as “local variables inside the function”. You wouldn’t want someone calling your function and messing with the local vars, and you wouldn’t want someone using your object messing with its private members.

Magic methods provide functionality like catching references to methods and properties which are not visible to us, and doing special things with them. Magic methods have always struck me as a bit weird, and whenever you bring them up in discussions online, there’s always a few people with reservations about them – efficiency, clarity, use-cases and so on.

I’m still in two minds; they can be useful in some circumstances, but here’s one reason why they could be considered harmful: Used carelessly, they can easily enable an OOP antipattern where all class members become public, even those declared as private or protected in the class definition. Read the rest of this entry »

, , , , , , , , , ,

7 Comments

Overloading in PHP

Murray Picton wrote up a blog post today on overloading functions in PHP. Overloading is a useful feature of many languages. Murray gives a nice definition in his post:

Overloading a function is the ability to define a function more than once with a different set of parameters for each one and then when it is called, the version of the function that matches the parameter set will be executed.

so you can define function foo(String $a) and foo(Array $a) and a different version will be called depending on how you call it. But, PHP’s idea of overloading is completely different and not really related.

Hello ladies, look at PHP, now back to Java, now back to PHP. Sadly, PHP’s not Java, but it can look (a bit) like Java if you stop using lady-scented functions and start using method overloading.

I just wanted to get that quote in somehow.

Murray’s solution is to use func_get_args inside your function, and perform some logic to switch execution to a different branch depending on what we find there. Something like:

function foo() {
    $args = func_get_args();
    if(is_string($args)) { /* do some stuff */ }
    else if(is_array($args)) { /* do some stuff */ }
}

This works well enough, but there are a few things I don’t like about it:

  1. You have to put all the code into one function, instead of literally overloading multiple functions
  2. The “which version am I” code and the actual functionality are intermixed inside the function

I thought an OO solution might mitigate against these things, allowing us to write completely separate functions, but which can be called with the same name, a different one being executed depending on the arguments. I’m not certain my solution is an improvement over Murray’s, but it’s a different approach if nothing else:

Read the rest of this entry »

, , , , , , , ,

5 Comments

JS1k Winners – Top Ten Entries

So, the JS1k contest is over and the winners are finally in! What a fantastic event this has been, massive thanks to all the organisers and judges, and to all the entrants for putting on a great show, I can’t think of a single entry I wouldn’t have been proud to have written myself, and some of the entries were simply amazing.

The judges did a brilliant (and difficult!) job of ranking the entries and choosing their top ten. I’ve compiled the entries into a list below, and you can click through to the demos themselves from here. I read on twitter that the official site will be updated tonight, so check back at js1k.com for the full scoop :)

If this is the first you’ve heard of the contest, head over to js1k.com and browse through all the entries. I also compiled a list of all the tweet-sized entries, as I’m buying a copy of Douglas Crockford’s JavaScript:The Good Parts as a prize for the best tweetable entry. Have a look at my own tweetable entries too.

Read the rest of this entry »

, , , , , ,

2 Comments

Some tweetable #js1k demos

JS1k is consuming me at the moment. I saw this entry by strager and it inspired me to push for a tweetable (<=140 byte) demo based on his.

By dropping the save/restore and alpha blending features, I was able to come up with a few candidates which I think look fairly pretty.

Unlike my previous allRGB and rot13 entries, where I had a definite goal in mind, here I’m really just playing with parameters until something cool appears on the screen. Which is kinda neat, it recaptures that innocent experimental spirit which was what first attracted me to programming when I was a kid.

Read the rest of this entry »

, , , , ,

13 Comments

Some thoughts on JavaScript

I don’t know about you, but I grew up doing image rollovers in JS and other groundbreaking “dhtml” stuff. Since then CSS has evolved, web standards and browsers have evolved, and things are much much nicer than before.

One thing that is starting to change is the way we fundamentally approach javascript. Not simply the recent popularity of libraries such as jQuery, allowing us to literally “change the way we write javascript”, but also there’s now much more awareness of the power that javascript has, and we’re doing more mission-critical stuff with JS. We’re moving from favouring simple procedural snippets of javascript that add twinkles to the page to fully object oriented JS applications, exporting great swathes of functionality away from the servers and onto the client.

This is a great thing. In fact it’s little short of a miracle; the servers are running faster and so are the clients! There seems to be no trade-off; by deeply integrating JavaScript into our web applications we’ve gained speed at both ends!

Not quite though.

Read the rest of this entry »

, , , ,

No Comments

Fast PHP array_unique for removing duplicates

PHP’s native dedupe function, array_unique, can be slow for large amount of input. Here I’m going to talk about a simple function that performs the same task but which runs a lot faster.

Often, people spout PHP optimisation advice that is incredibly misguided, so I want to make it clear up-front that you should be benchmarking your scripts using xdebug before you start optimising, and very often the real bottlenecks cannot be avoided by using “micro-optimization”. Here’s a nice PDF on Common Optimization Mistakes.

Now I’ve got that disclaimer out of the way, I believe it’s OK to talk about making a faster array_unique because it’s often used on large amounts of data – for example removing duplicate email addresses, and as such there are genuine use cases for a fast array_unique in PHP. Also our fast_unique function can be several seconds faster than array_unique so we’re not necessarily talking about micro-optimisation here; on 200k duplicate entries, array_unique takes nearly 5 seconds on my windows dev box, fast_unique takes <1 second on the same data. On 2 million entires the results are staggering – performance graphs are given below (but then, why are you doing that kind of work in PHP?).

The function looks like this:
Read the rest of this entry »

, , , , , , , ,

4 Comments

Caching in Javascript with Cachejs

Here’s a useful open-source (MIT license) javascript caching object I developed for my job at GG.com, the best horse racing site on the net.
(I am contractually obliged to say that every time I mention the URL. Not really though).

Like most web applications these days, we make fairly extensive use of Ajax, sending and receiving JSON data across the net on hover events and so on.

However, we’ve found that all those HTTP requests can slow down the user experience, and causes unnecessary extra load on our application servers, so we decided to employ a client-side Least Recently Used (LRU) caching object, so that we can reduce the number of HTTP requests, and increase the response speed for cachable queries. It employs lazy garbage collection, just like memcached does. In fact we see this as a kind of “memcache for javascript”, if that makes any sense at all.

It depends upon no external libraries. Here’s a simple usage example:

Read the rest of this entry »

, , , , , , , , , , , , , ,

2 Comments

XKCD Colour Survey – a 3D visualisation

Randall Munroe (of XKCD) has been running a “name the colour” survey for the last few months and today released the data. The results are broken down by gender, and he makes some fascinating obvservations.

I’ve been working on a colour-related project on and off for about a year now, and part of that has involved creating visualisations of the RGB colour space – plotting red on the X axis, blue on Y, green on Z. So I thought it would be interesting to map XKCD’s 954 most common colour names in three dimensions – his charts are nice n’ all, but sexy javascript 3d is, well, sexier:

XKCD Colour Names in 3d

If you click that, you’ll be taken to the demo page, where you can interact with the cube. It’s a bit juddery, working entirely with divs and DOM manipulation, rather than canvas. Here’s a view from the side angle that shows off the “3d-ness” a bit more:

Of course, a canvas is really a better solution, so here’s a version that renders onto canvas, which is much much faster, but currently omits the names:

Read the rest of this entry »

, , , , ,

15 Comments

Fast PHP – effective optimisation and bottleneck detection

PHP is not the fastest language on earth. That honour probably goes to machine code. But like many high-level languages, PHP provides some handy abstractions, like named variables, hashmaps (associative arrays), a C-like syntax, object oriented capabilities, loose typing and so on – we trade processing speed for development ease.

So it’s quite a common problem that people find their large PHP web applications running quite slowly.

Here are some frequently encountered bottlenecks found in web applications generally, and PHP specifically:

Read the rest of this entry »

, , , , , , ,

13 Comments