All posts by matt

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

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 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

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

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:

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:

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:



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.

$("#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:

public static final Elvis INSTANCE = new Elvis();

or a static factory:

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!

// Enum singleton - the preferred approach
public enum 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 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.

Update: Much easier way with new free website:

www.oddprints.com

 

You can use that site for any size frame like 2″x2″ or whatever. Simple!

 

If you like pain, here’s the old command-line way:

  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

Selecting Child Entities with GQL Queries

In Google App Engine, you can create owned one-to-many relationships between entities. The classic example you were taught at uni is that a Book owns a Chapter, which in turn, owns a Paragraph. For my site, stolencamerafinder, the example is that a camera Make owns a set of Models.

If you want to query for the model directly in GQL (from the app engine dashboard for example) you can create the key by specifying the full parent chain:

SELECT * FROM Model where __key__ = KEY('Make', 'canon', 'Model', 'canon eos 5d')

Google’s GQL reference was a little sparse on this syntax so I’m posting it here in the hope you find this faster than I worked it out.

For completeness, this is the difference it makes in JDO. My old code looked something like this:

PersistenceManager pm = PMF.get().getPersistenceManager();
Key makeKey = KeyFactory.createKey(Make.class.getSimpleName(), makeName);
Make make = pm.getObjectById(Make.class, key);
List<Model> models = make.getModels();

for (Model model : models) {
    if (model.getName().equals(modelName)) {
        return model;
    }
}

It doesn’t take much imagination to realise this doesn’t scale very nicely as the number of models increases. The new code looks like this:

PersistenceManager pm = PMF.get().getPersistenceManager();
Key makeKey = KeyFactory.createKey(Make.class.getSimpleName(), makeName);
// Can create the Model key by specifying parent key...
Key modelKey = KeyFactory.createKey(makeKey, Model.class.getSimpleName(), name);
// Bam! Get the child entity in a single query
Model model = pm.getObjectById(Model.class, modelKey);

I wouldn’t have noticed this performance bottle neck if it wasn’t for appwrench. It looks a little dead to be honest, but works well.

Tips for better low-light wedding photos with a Canon DSLR.

I just got this in an email:

A friend has asked me to take some of their wedding photos with their Canon 1000D. Had a play with it yesterday and I’m finding the flash a bit harsh. Is there a top tip to minimise this?

Firstly, if you’re using the camera in the day near natural light, the camera will be fine and it’s all down to your artistic flair.

For evening shots, I’ve written a bunch of tips, but really, there is only one:

  • Borrow a Canon Speedlite that supports ETTL. (eg, the 430EXii or 580EXii).

Seriously. If you know someone into their photography that may have one you can borrow, give them a ring. Slap it on the camera, press “mode” until it says “ETTL” on the screen, aim the flash so the light bounces of a wall/ceiling to your subject (pool skills handy here) and snap away. The rest of the tips may help prevent you taking a load of unusable shots, but if you get a speedlite, you will take the best shots of the whole day (perhaps including the photographer’s).

If you can’t get a speedlite, my next-best advice is to wait for the sun to come up or get your subject under some other light source. On-camera flash is ugly, and unflattering. I have a top-end Canon and I never use the on-camera flash on people because they’ll just look sweaty and wrinkly. If you can get people next to a lamp or something, you’ll have much more luck.

If neither of those tips will help you, here are what I consider to be “last resort” tips:

  • Prop camera against wall or on table for a steadier shot.
  • Try self timer with camera on table.
  • Form triangles with your body (tuck elbows in to sides) to become human tripod. Remember to look like a pro by cupping the lens with left hand palm upwards.

Anti-tips! Don’t do this:

  • Raise the ISO above 800. Ideally, keep the ISO at 400 or lower unless you like grainy photos.
  • Stick a Rizla to the flash. It will not soften the light, it just drinks the battery.

Keeping the camera steady will mean sharper shots, but if your subjects move, you’ll still get blurry shots. But I say go with it. Asking people to stay still means awkward faces. A blurry shot of someone laughing / dancing is a good thing if it’s deliberate.

My favourite wedding photos are always in the evening when people are relaxed (read: drunk). I’m sure you’ll capture some gems.

How to update the lastmod date in your sitemap xml with Ant

Hmm, you want to add the “lastmod” node, but you’re too lazy to ever keep that up to date so you decide to update it with your Ant script whenever you deploy. Easy.

So you’ve just written a valid sitemap.xml file for your website because Google said it was a good idea. Great.

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
   <url>
      <loc>http://www.stolencamerafinder.com/</loc>
      <lastmod>2011-04-21</lastmod>
      <changefreq>weekly</changefreq>
   </url>
</urlset>

First, you’ll need the jar for a third-party Ant task called XMLTask. Once you have that, the ant target you’ll need is simply:

<taskdef name="xmltask" classname="com.oopsconsultancy.xmltask.ant.XmlTask" classpath="test-lib/xmltask.jar"/>
<target name="update-sitemap" description="update the update date">
	<tstamp>
	    <format property="today" pattern="yyyy-MM-dd" locale="en,UK"/>
	</tstamp>
    <xmltask source="war/sitemap.xml" dest="war/sitemap.xml" standalone="yes" report="true">
        <replace path="/:urlset/:url/:lastmod/text()" withText="${today}"/>
    </xmltask>
</target>

Yeah yeah, this is kid’s stuff, why blog about it? Well, embarrassingly, it took me 3 hours of messing around to get it working. If I don’t write it down somewhere, I’ll only forget the next time I need to do this. Sigh.

How to detect browser support for File Api and drag and drop with javascript

Here’s a bit of info for you crazy HTML5 kids. You’ll need to include the handy Modernizr script for it to work.

var browserIsSupported = !!window.FileReader && Modernizr.draganddrop;
If you want see it in action, just visit stolencamerafinder 😉
I’ve tested this in Firefox 3.6, Chrome 10, IE8, Safari 5 and Opera 11. The only browsers from that list to support FileReader from the File API and the drag and drop events are FF and Chrome.
Let’s hope the other catch up soon…