Testing JavaScript with QUnit for for Dummies, sorry, Java developers

Disclaimer: I’m no javascript expert so I may be am almost certainly talking a load of rubbish here.

I was just looking for a unit testing framework for some javascript I’m writing (rather the the home-rolled framework I’ve out-grown) and came across QUnit. I’ve not tried any others so feel free to suggest alternatives. So far, it’s great and does everything I want and took me almost no time to learn. Easy.

The one thing that bugs me though is that they’ve swapped “expected” and “actual” parameter arguments around for the equality test. Technically it’s not that important since it won’t affect the result of the test, but in practice I think it’s very important. Your tests form part of your documentation of how the code should behave. If you get them the wrong way around and a test fails with “expected 10 but got 20″ the developer may well go off and try to make the code return 10. *shudder*.

Java method signature in JUnit:

1
public static void assertEquals(Object expected, Object actual)
public static void assertEquals(Object expected, Object actual)

The class offers overloaded implementations with primitives or with message etc. There are also ways of writing your tests in a type-safe fashion to prevent this whole problem in Java, but in my experience, this is more common. Another post maybe…

Javascript function signature in QUnit:

1
equal( actual, expected, [message] )
equal( actual, expected, [message] )

I can only assume they reversed the order of the arguments because of the way that javascript allows optional arguments.

I flip between writing Java and JavaScript quite a lot which would be a disaster waiting to happen so I’ve just wrapped it in my own function:

1
2
3
function assertEquals(expected, actual, message) {
    equal(actual, expected, message);
}
function assertEquals(expected, actual, message) {
    equal(actual, expected, message);
}

This all feels wrong and stupid. What do you think?

The cheapest way to get a Samsung Galaxy S2 in the UK

If you’re a materialistic idiot like me, you’ll be interested in how you can get your hands on a disgustingly extravagant smartphone while parting with the least amount of cash possible.

The best deal I found for the Galaxy S2 (by far) has been through Tesco:

  • Free handset
  • T-Mobile network
  • 300 mins/300 texts
  • 24 month contract
  • Free delivery
  • 500MB Data Booster + Unlimited Internet
  • £20 of free apps available (through some T&Cs)
  • £20.42 per month
At time of writing, that is the best deal I could find and is even better than anything I could find through the (usually excellent) billmonitor website.
Chances are that deal should work out just fine for you. If so, I hope this post helped you out.

 

Current T-Mobile customers:

If (like me) you are already a T-Mobile customer then the checkout procedure will fail right at the end with an error code “existing customer“. I went into the tesco mobile shop and was told that the only way around it was to switch to a PAYG contract, then try again. This was a bit of a pain and I won’t bore you with the series of contradicting advice I got from T-Mobile on the matter. If you’re a T-Mobile customer, you have to do the following:
  1. Buy a PAYG sim card (I got one for £11.99 with £10 credit from Three but you can get cheaper).
  2. Ring T-Mobile. Tell them you wish to cancel. Also request a Porting Authorisation Code (PAC) so that you can keep my number. Your account isn’t actually closed until the number is ported.
  3. Contact your PAYG sim network to port your number. For Three there is an online form under “Bringing your number to Three”.
  4. Once your number has been ported onto your PAYG sim (mine took 1 day) you can order your phone from Tesco.
There are a few quirks with the tesco order form. For example, entering a landline number is mandatory and a mobile number is not accepted. I just made up a number and it still worked. Also, it asked me to enter my name as it appears on the card (MR M J BURNS) but then complained that my first name was too short.  I entered both my initials in the firstname box and that worked.

 

Alternatives

The Google Nexus is the new kid on the block but costs big bucks at the moment. There’s also an upgraded Galaxy S2 in the form of the Galaxy S2 HD LTE floating around Japan. Don’t get too excited though, this isn’t coming to the UK for ages and there’s no foreseeable plans for a decent rollout of a 4G network in the UK for quite a while anyway. You should also consider if you can afford to commit to 24 months for a phone that won’t make your life any better/easier/happier. It’s just a phone. Pah, who am I kidding, it’s a work of art and object of pure desire!

 

Conclusion

Getting your hands on this Tesco deal can be a bit of hassle, but when you look at the savings over 24 months, completely worth it.
I hope this helps you if you’re in the market for a top smartphone.

Simplify your API – Can Singletons be used for Good, not Evil?

I recently wrote an article about singletons in java. The only thing I wanted to cover was that if you really want a singleton, I recommend you use the enum pattern. This post was motivated after more interesting comments were raised about testability when you see the “static” keyword.

When you type “static” a little alarm bell should ring in your head to warn you that there could be trouble ahead. As Dan correctly pointed out, a reference to the static member INSTANCE will tightly couple the caller to Elvis. This is not good if testing with Elvis will cause you problems. For example, if Elvis is slow, or accesses a database or something like that which would be better tested with a mock implementation.

However, sometimes the static keyword makes sense because it is an implementation detail that you are not concerned with. By you I mean a client of the code. Why muddy an API so that you can pass around objects that will never change. To illustrate my point, I wrote a very simple bit of code that hopefully isn’t too contrived.

Imagine you have to write a computer system for a Blackpool nightclub called “Elvis Live!”. This club has a different Elvis impersonator on every night. The system has to manage the bookings of the different Elvis impersonators and print the posters which list which impersonators are performing each night.

In my very simple implementation I wrote a class to represent the club:
ElvisClub.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package uk.co.mattburns.elvis;
import java.util.Map;
import org.joda.time.LocalDate;
import com.google.common.collect.Maps;
 
public class ElvisClub {
 
    private final Map<LocalDate, ElvisImpersonator> bookings = Maps
            .newTreeMap();
 
    public boolean bookImpersonator(LocalDate date,
            ElvisImpersonator impersonator) {
        if (bookings.containsKey(date)) {
            return false;
        } else {
            bookings.put(date, impersonator);
            return true;
        }
    }
 
    public ElvisImpersonator getImpersonatorOnDate(LocalDate date) {
        return bookings.get(date);
    }
 
    public String getPosterTitle() {
        return "Keeping The King Alive since " + Elvis.INSTANCE.died();
    }
 
    public String getPosterBody() {
        StringBuilder stringBuilder = new StringBuilder();
        for (LocalDate date : bookings.keySet()) {
            ElvisImpersonator act = bookings.get(date);
            stringBuilder.append(date.toString() + " : See " + act.name());
            stringBuilder.append(" who was born " + act.yearsBornAfterElvis()
                    + " years after Elvis");
        }
        return stringBuilder.toString();
    }
}
package uk.co.mattburns.elvis;
import java.util.Map;
import org.joda.time.LocalDate;
import com.google.common.collect.Maps;

public class ElvisClub {

    private final Map<LocalDate, ElvisImpersonator> bookings = Maps
            .newTreeMap();

    public boolean bookImpersonator(LocalDate date,
            ElvisImpersonator impersonator) {
        if (bookings.containsKey(date)) {
            return false;
        } else {
            bookings.put(date, impersonator);
            return true;
        }
    }

    public ElvisImpersonator getImpersonatorOnDate(LocalDate date) {
        return bookings.get(date);
    }

    public String getPosterTitle() {
        return "Keeping The King Alive since " + Elvis.INSTANCE.died();
    }

    public String getPosterBody() {
        StringBuilder stringBuilder = new StringBuilder();
        for (LocalDate date : bookings.keySet()) {
            ElvisImpersonator act = bookings.get(date);
            stringBuilder.append(date.toString() + " : See " + act.name());
            stringBuilder.append(" who was born " + act.yearsBornAfterElvis()
                    + " years after Elvis");
        }
        return stringBuilder.toString();
    }
}

A simple pojo to represent a performer at the club:
ElvisImpersonator.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package uk.co.mattburns.elvis;
import org.joda.time.LocalDate;
 
public class ElvisImpersonator {
 
    private final String name;
    private final LocalDate birthdate;
 
    public ElvisImpersonator(String name, LocalDate birthdate) {
        this.name = name;
        this.birthdate = birthdate;
    }
 
    public String name() {
        return name;
    }
 
    public LocalDate birthdate() {
        return birthdate;
    }
 
    public int yearsBornAfterElvis() {
        return birthdate().getYear() - Elvis.INSTANCE.born().getYear();
    }
}
package uk.co.mattburns.elvis;
import org.joda.time.LocalDate;

public class ElvisImpersonator {

    private final String name;
    private final LocalDate birthdate;

    public ElvisImpersonator(String name, LocalDate birthdate) {
        this.name = name;
        this.birthdate = birthdate;
    }

    public String name() {
        return name;
    }

    public LocalDate birthdate() {
        return birthdate;
    }

    public int yearsBornAfterElvis() {
        return birthdate().getYear() - Elvis.INSTANCE.born().getYear();
    }
}

Crucially, both of these classes have a dependency on Elvis. I decided to make Elvis a singleton:
Elvis.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package uk.co.mattburns.elvis;
import org.joda.time.LocalDate;
 
public enum Elvis {
    INSTANCE;
    private final LocalDate born = new LocalDate(1935, 1, 8);
    private final LocalDate died = new LocalDate(1977, 8, 16);
 
    public LocalDate born() {
        return born;
    }
 
    public LocalDate died() {
        return died;
    }
}
package uk.co.mattburns.elvis;
import org.joda.time.LocalDate;

public enum Elvis {
    INSTANCE;
    private final LocalDate born = new LocalDate(1935, 1, 8);
    private final LocalDate died = new LocalDate(1977, 8, 16);

    public LocalDate born() {
        return born;
    }

    public LocalDate died() {
        return died;
    }
}

You can browse all the source code here. Or better still, checkout the code and simply import the project into eclipse:

svn checkout http://elvis-club.googlecode.com/svn/trunk/ elvis-club-read-only

 

I already know what you’re thinking:

Elvis.java should be an interface: Celebrity.java. Then I could have a concrete Elvis to pass around which implements Celebrity.

ElvisImpersonator.java should be an interface: Impersonator.java. Then I could write a CelebrityImpersonator.java which would take a Celebrity on construction.

That is one way of solving it, and it’s not a bad way. I agree that you should expect change, embrace it, marry it, have its babies, but don’t start writing code for it before it’s happened. One day the club may have a Marilyn Monroe night and in that case you anticipated change beautifully luckily. What if it changes into a comedy club? How about a restaurant?

What’s really important is writing code that’s easy for programmers to read, and therefore, easy for programmers to change.

Here is a snippet from some of my test code which gives you an idea of what I mean:

1
2
3
4
5
ElvisClub theClub = new ElvisClub();
LocalDate today = new LocalDate();
LocalDate brianBorn = new LocalDate(1970, 1, 1);
ElvisImpersonator brian = new ElvisImpersonator("Brian", brianBorn);
theClub.bookImpersonator(today, brian);
ElvisClub theClub = new ElvisClub();
LocalDate today = new LocalDate();
LocalDate brianBorn = new LocalDate(1970, 1, 1);
ElvisImpersonator brian = new ElvisImpersonator("Brian", brianBorn);
theClub.bookImpersonator(today, brian);

A similar snippet, without using the Elvis singleton would look something like this:

1
2
3
4
5
6
7
8
LocalDate brianBorn = new LocalDate(1970, 1, 1);
LocalDate elvisBorn = new LocalDate(1935, 1, 8);
LocalDate elvisDied = new LocalDate(1977, 8, 16);
 
Celebrity realElvis = new CelebrityImpl("Elvis", elvisBorn, elvisDied);
Impersonator brian = new CelebrityImpersonator("Brian", realElvis, brianBorn);
Club theClub = new Club(realElvis);
theClub.bookImpersonator(today, brian);
LocalDate brianBorn = new LocalDate(1970, 1, 1);
LocalDate elvisBorn = new LocalDate(1935, 1, 8);
LocalDate elvisDied = new LocalDate(1977, 8, 16);

Celebrity realElvis = new CelebrityImpl("Elvis", elvisBorn, elvisDied);
Impersonator brian = new CelebrityImpersonator("Brian", realElvis, brianBorn);
Club theClub = new Club(realElvis);
theClub.bookImpersonator(today, brian);

There’s not a massive difference but I still think the constructors are a bit “noisy”. In a real-world application, you would probably expect references to a more complex set of collaborating objects.

I haven’t sacrificed any testibility of my code. If anything, I’ve reduced the amount of code I need to test. My way, there can only be Elvis and so I only need to test that the club handles things to do with Elvis. If I wrote a more generic version I would have to test that it handles Celebrities that are still alive, that they were born before they died, and so on.

I think I’m right but I’ve changed software design views pretty frequently over the last 10 years. If you think I’m wrong, I challenge you to convince me why…

Bug with JQuery validation error messages showing tooltip text

I had the following html in my form:

1
2
3
4
<label for="email-input">Email</label>
<input id="email-input"
       type="text"
       title="Don't worry, your email will not be displayed on the website or given to anyone else. We hate spam too." />
<label for="email-input">Email</label>
<input id="email-input"
       type="text"
       title="Don't worry, your email will not be displayed on the website or given to anyone else. We hate spam too." />

Nothing complicated there I hope.
I had the help text set in the title attribute of the input which I styled with the lovely qTip to make it look nice. I validated my entry using the jQuery validation plugin which also works well. The problem is that if an attempt is made to submit the form before any attempt at editing the value or showing the tooltip, the error message would show the value of the tooltip (“Don’t worry…“) instead of the validation error message (“This field is required“).

It’s taken me a while to find the cause, but the fix is easy. When invoking the validator, throw in the option to ignore title attributes.

1
2
3
$("#your-form").validate({
ignoreTitle: true
})
$("#your-form").validate({
ignoreTitle: true
})

How to enable Offline Google Docs for Google Apps users

Do you still not have the offline option for Google Docs?

If you’re a Google Apps user, then your apps administrator has to enable it first:

  1. Log in to the Google Apps control panel at https://www.google.com/a/your_domain.com (replace your_domain.comwith your actual domain name).
  2. From the menu bar at the top of the page, click Settings.
  3. In the left menu, click Docs.
  4. Select the Allow users to enable offline docs check box.
  5. Click Save changes.

Then your users can choose to set it up in the same way normal gmailers can with the docs cog in the corner:

set up offline docs

Hope this helps you out.

Matt

How to write Singletons in java

Singletons get a pretty bad press. Often described as an “anti-pattern”. I think it’s a little unfair since I find them pretty useful in several situations. However, the reason they can be bad is important to understand:

Making a class a singleton can make it difficult to test its clients, as it’s impossible to substitute a mock implementation for a singleton unless it implements an interface that serves as its type.

That quote, and most of what I am about to write are completely stolen from Josh Bloch’s excellent book, Effective Java (highly recommended in paperback or kindle editions). Those are affiliate links, but I still recommend you buy it no matter where you get it from.

Anyway, it raises an important point about testability, but one that I think doesn’t matter. The way I see it, if you’re writing a singleton that represents something you want to swap with a mock, such as a database connection or network resource etc then your design will change as your tests evolve. You practice TDD right? You’ll soon realise that a singleton doesn’t make sense or you need an interface of some kind. This post is about how to write a good singleton.

In the bad old days before java 1.5 there were 2 common ways to implement a singleton. A public final field:

1
public static final Elvis INSTANCE = new Elvis();
public static final Elvis INSTANCE = new Elvis();

or a static factory:

1
2
3
4
private static final Elvis INSTANCE = new Elvis();
public static Elvis getInstance() {
    return INSTANCE;
}
private static final Elvis INSTANCE = new Elvis();
public static Elvis getInstance() {
    return INSTANCE;
}

The static factory version is slightly better in that the you have a bit more flexibility to change your implementation details at a later date. In my two examples there is no performance benefit of either technique in modern JVMs. This is all well and good. There is only one Elvis in the world. There is the possibility a privileged client can invoke the private constructor reflectively but I’m not going to dwell on that.

Bloch raises another problem:

To make a singleton class that is implemented using either of the previous approaches serializable, it is not sufficient merely to add implements Serializable to its declaration. To maintain the singleton guarantee, you have to declare all instance fields transient and provide a readResolve method. Otherwise, each time a serialized instance is deserialized, a new instance will be created, leading, in the case of our example, to spurious Elvis sightings.

Oo-er, this sounds messy. You implied in java 1.5 there’s a better way, please, what is it, I’m desperate!

1
2
3
4
5
// Enum singleton - the preferred approach
public <strong>enum</strong> Elvis {
    INSTANCE;
    public void leaveTheBuilding() { ... }
}
// Enum singleton - the preferred approach
public <strong>enum</strong> Elvis {
    INSTANCE;
    public void leaveTheBuilding() { ... }
}

TADA!

This approach is functionally equivalent to the public field approach, except that it is more concise, provides the serialization machinery for free, and provides an ironclad guarantee against multiple instantiation, even in the face of sophisticated serialization or reflection attacks. While this approach has yet to be widely adopted, a single-element enum type is the best way to implement a singleton.

Have a little think about it, let it sink in, then run off and replace any singletons in any projects you can get your hands on.

How to dynamically choose the color of your Google maps marker pin using javascript

You can dynamically request icon images from the Google charts api with the urls:

http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|FE7569

Which looks like this: default the image is 21×43 pixels and the pin tip is at position (10, 34)

And you’ll also want a separate shadow image (so that it doesn’t overlap nearby icons):

http://chart.apis.google.com/chart?chst=d_map_pin_shadow

Which looks like this: shadow the image is 40×37 pixels and the pin tip is at position (12, 35)

When you construct your MarkerImages you need to set the size and achor points accordingly:

var pinColor = “FE7569″;
var pinImage = new google.maps.MarkerImage(“http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|” + pinColor,
new google.maps.Size(21, 34),
new google.maps.Point(0,0),
new google.maps.Point(10, 34));


var pinShadow = new google.maps.MarkerImage(“http://chart.apis.google.com/chart?chst=d_map_pin_shadow”,
new google.maps.Size(40, 37),
new google.maps.Point(0, 0),
new google.maps.Point(12, 35));

You can then add the marker to your map with:

var marker = new google.maps.Marker({
position: new google.maps.LatLng(0,0),
map: map,
icon: pinImage,
shadow: pinShadow
});

Simply replace “FE7569″ with the color code you’re after. Eg: yellow

How to get the “WINDOWS USB Driver” for your LG mobile

If you’re trying to update your LG mobile (I’m doing my LG Arena KM900) you will be taken to a page that tells you to install the WINDOWS USB Driver, whatever that is.

At time of writing, that link doesn’t work.

Don’t worry, just go ahead and click “Software Update” as there is the option to install the usb driver there. If you also need the PC Suite, I found a copy here.

My next e-book

If you know me, you’ll know I just got back from a year galavanting around the world. I was given a Sony e-book as a present which I took with me, and soon became an essential item.

It’s already showing its age compared to newer models but I’m not buying a new one until e-book manufacturers start adding features I actually want.

I don’t want:

  • A colour screen. Why would I? I just want a book
  • Video support. If I wanted an iPad, I’d buy an iPad. I just want a book.
  • A qwerty keyboard. I have a phone for web and email. Did I mention I just want a book?

I want:

  • A big screen. Y’know, about the size of a book. With the best resolution you can please.
  • Amazing battery life. My current e-book is fine but more is always welcome. If the battery won’t easily last a week, then a book wins.
  • Tough construction. I don’t want to feel I have to buy a leather case to protect my delicate gadget and then just worry about it in my backpack. Make it tough so I can just chuck it around. Like a book.
  • Water-proofing. This is the killer feature. I want to read on the beach and in the bath without worrying about it. Why isn’t there a bright yellow* ‘sport’ edition like the walkmans of the 90′s?

I already prefer my e-book to real books. It’s a no-brainer for me, I’m converted. But if you’re a manufacturer and you want me to upgrade, make a model with features I actually care about.

*Yellow would obviously be an awful colour for a book. Black or white would probably sell better but frankly, I don’t care**.

**I’m lying, of course I would care. How about carbon fibre? Transparent plastic? Metal covered in that rubber they make Aerobies with?

How to print small photos (say, 4cm x 4cm)

If you have a photo you want to put into a small frame, you may struggle finding a print company that print photos smaller than 15cm x 10cm (6″x4″).

The simple answer is to create add a white border to your jpeg and print that. Then you can just trim the edges off the print. I just tried this and it was harder than I would have liked. If you open your photo in some software and expand the canvas, you’ll find it will start eating lots of memory. On my little laptop it became impossible to use.

I found the best way was to use the command line. It’s really simple:

  1. Install imagemagick. It’s free and very powerful.
  2. Open a command prompt (on windows: Start > Run > “cmd”)
  3. Type the following command (replace the path to convert.exe and input.jpg filename as necessary):

“C:\Program Files\ImageMagick-6.6.0-Q16\convert.exe” input.jpg -border 137.5%x75%  output.jpg

This example only work with square input photos. Here’s a table to help you work out how to print other sizes. If you have a size you want me to add, just drop a comment.

input ratio desired print size border to add print size to order
1:1 4cm x 4cm 137.5%x75% 15cm x 10cm
3:2 6cm x 4cm 75%x75% 15cm x 10cm