Java interface and implementation naming (or “I” or “Impl”)

How do I name my interfaces and the classes that implement my interfaces? Through much research on the internet and my own gut feelings, this is what I reckon:

I never prefix my interfaces with “I”. The value of coding to interfaces is that you can swap out the implementation with minimal hassle. It means that instead of using implementation specific class names in your code, you use interface names instead – right? So, if I’m going to be using interface names everywhere, I don’t want to have to prefix everything with “I”. Coding to interfaces is a best practice, so I don’t need to explicitly state that I am doing it…It should just happen – which makes the “I” prefix redundant.

Furthermore, the “Impl” suffix is also redundant. Yes, indeed, your dilemma isn’t as simple as picking between the two. Firstly, “Impl” doesn’t translate. “Impl” in other languages has no meaning, and yes I’m talking about Polish and Scala. In Polish (according to Google translate), “implementation” is “realizacja” and in Scala, there are no interfaces. The closest thing Scala has to interfaces is traits, which can contain implementation specific code. So really, everything is Scala is an implementation, so why you use “Impl” suffix?

Secondly “Impl” is restrictive. What happens when you want to add another implementation of Foo? You gonna call it “FooImplImpl”? “AnotherFooImpl”? “FooImpl2″? I didn’t think so. Perhaps you were going to just call it “FooImpl” and put it in a different package…

Thirdly “Impl” doesn’t convey any meaning about what the implementation is. You wouldn’t create an “AnimalImpl” would you? You’d create a “Lion” or an “Elephant”. There is almost always something that distinguishes your implementation that you can use in the class name. Even if it is a long name, it doesn’t matter – you’re coding to interfaces (remember?), so you’re rarely going to see that class name.

Lastly, and probably most importantly – you still can’t think of a name? You don’t need an interface. If you really can’t think of a name, your class must be generic enough to not need an interface and you’re probably not going to have any other implementations. Your class methods become the interface contract, and that is that.

LESS CSS clearfix

The fantastic clearfix, as a LESS CSS class:

.clearfix {
    zoom: 1;
    &:before, &:after {
        content: "";
        display: table;
    }
    &:after {
        clear: both;
    }
}

Use in your code like so:

ul#gallery {
    .clearfix;
    li {
        float: left;
    }
}

Easy.

Extensions to Spring’s FreeMarker macro’s (spring.ftl)

Spring’s FreeMarker macro’s are pretty useful, but there are a couple of things I need from the showErrors macro that simply aren’t there:

  1. Show errors without a HTML tag around them – if you don’t specify a classOrStyle, the showErrors macro will wrap your error message in a <b> tag. If you do, it’ll wrap it in a <span> (understandably)
  2. Pick the tag that surrounds each message – As explained in the first point, you can see we only get the choice of <b> or <span>. What if I wanted to use an <li>? …use the separator? – no good, because unless I write an <#if> statement to check the number of error messages before I call showErrors I’ll end up with redundant <ul>/<ol> and <li>’s in my markup if there aren’t any errors:
    e.g. <ul><li><@spring.showErrors “</li><li>”/></li></ul>
    Which leads me nicely onto the next point:
  3. Show errors in an ordered/unordered list, automatically detecting zero messages and not outputting markup if this is the case
  4. Show errors for multiple bind paths – Spring’s showErrors only shows errors for the currently bound field. However I’ve found that I’ve needed to show errors for 2 or more fields together. This is particularly true of a DOB field where the day/month and year are separate <select>’s
  5. Finally, show errors for multiple bind paths, in an unordered/ordered list

You can download my Spring extensions here: springx.ftl. Inevitably I’ll find more bits and pieces to add and will update them accordingly.

JSIO Performance Results

Below are two graphs plotting the number of images on a page against the total KB transferred by Chrome 13 for both a page with JSIO and without JSIO (which I, for some reason have called a “plain” page).

I build websites for a living, so I have a lot of folders of images from various websites lying around which form the two data sets for the graphs. I’d like to think of them as a typical set of website images, but you may argue that they are typical for the websites that I build.

I knocked up a script that when given a folder of images, will output a “plain” HTML page, a JSIO HTML page and a JSIO resources file with the following numbers of images on them: 2, 4, 6, 8, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000 and 1100. Before generating any of the pages, the order of the images were randomised to better represent a web page’s inclusion of different images for different purposes.

Chrome 13 was used with the developer toolbar to determine how many requests were being made and the actual KB transferred (with slight rounding errors) by the browser. In my opinion I would say that Apache was set up to serve image and javascript content typical of many servers on the internet in that images were not gzipped but javascript files were; the register, bbc, for example.

What is interesting to note is that the number of bytes transferred by JSIO are consistently lower than the bytes transferred by a plain HTML page…but not by a lot. The file size inflation due to base64 encoding seems to cancel out a lot of bytes the gained from making fewer requests. However, it is obvious that JSIO won’t actually lose you any bytes, but it isn’t going to save you a substantial amount. That said, saving bytes isn’t the only benefit of JSIO, remember that one of JSIO’s goals is also to alleviate some of the problems surrounding the creation and use of image sprites – which it does also do very well.

The graph below is just for fun, it plots the number of requests made by JSIO pages against the number of requests made by plain HTML pages. Note the JSIO pages make a constant 4 requests (index.html, jsio.js, jsio-resources.js and jsio.gif) independent of how many images are on the page:

I want my Snow Leopard functionality back!

Lion’s Mission Control is the closest thing I have to Snow Leopard’s Spaces. Generally, I’m fine with Lion. I’m used to the reverse scrolling and can just about deal with not knowing what I can and can’t scroll (although that is starting to grate), but the following things really affect me as they are “killer features” that I now don’t have:

  • No see “all windows in all spaces”. In Snow Leopard I had bottom left as my spaces hot corner and bottom right as my all windows hot corner. What was awesome was that I could trigger spaces at the bottom left, and then trigger all windows at bottom right – which meant I could see all windows in all spaces! Mission Control shows me all windows in the current desktop, but not all windows in other desktops…grrr
  • No moving windows between spaces/desktops. In Snow Leopard I used to be able to move windows between spaces, I cannot, in Lion, move windows between desktops…double grrr
  • No rearranging desktops in the order I want them. Also note that “Automatically rearrange spaces based on most recent use” is completely useless. I really don’t want Lion to move my furniture around…how am I ever going to find stuff if it isn’t left in the place I put it?

JSIO URLs

The clever bit about JSIO is the placeholder URLs – i.e. the “jsio.gif#…” that goes in your image src attributes and background-image CSS properties. Everything after the “#” is the filename of the image that should be displayed. It doesn’t have to be the filename at all, it could just be a single letter or number or symbol or whatever. It doesn’t matter to JSIO. To JSIO, everything after the “#” is just a key into the resources object that holds data uri encoded images. As long as the key is unique (which it will be if you use filenames, since no two files in the same directory can have the same name), JSIO is happy.

Using filenames as keys into our resources object is beneficial to humans. Much more beneficial than coordinates in a sprite, simply because (hopefully) the filenames are meaningful; they describe the image. In comparison to sprites, the JSIO resources object also makes maintaining your image data much easier as it is trivial to add or remove images without having to move other images around within the sprite (and consequently all coordinates referencing your moved image).

Another benefit of using filenames as keys into the JSIO resources object is for fallback. If JSIO detects your browser is IE7 or lower, it’ll strip out “jsio.gif#” leaving just your image key as the image src, which is hopefully a valid URL to the original image. Also, if JSIO detects you’re running IE8 and the image data is larger than 32KB it’ll do the same thing*.

* …but not yet in v1.0.0 alpha

Since the image key is after the “#” (it is the URL “fragment”), your browser won’t send multiple requests for the 1*1px jsio.gif file – it’ll just send one request, cache the response, and use it again. By the way, the jsio.gif image is just a transparent 1*1px gif (for maximum efficiency), but it could be an “spinner” image or something, which is shown temporarily whilst the JSIO resources file is downloaded.

This post is about JSIO – JSIO is a tiny library that allows you to make fewer requests to your server by packaging all your site image data in a JavaScript file in data uri format. The official site for JSIO can be found here: jsio.freestyle-developments.co.uk. You can read more about why I started this project here.

JavaScript Image Optimiser (JSIO)

So, I’ve embarked on a new mini project. It is kind of inspired by image sprites.

Image sprites are a great idea, but come with a whole bunch of issues that make them a bit of a pain to work with.

Firstly, most of the time you have to use markup to create an element in html to “hold” the image you wanted to display from your sprite. This is because if you actually set a sprite as the background image for a large html element you’re likely to see other images in the sprite as well. Because of this, you actually lose useful functionality that CSS gives you, like the ability to position, repeat and scale an image. Also, the markup you’ve created to hold the image exists for style purposes, which is bad.

Secondly, sprites can be a massive ball ache to maintain. If you’ve closely packed your images in a sprite for maximum efficiency and then one of your images needs to change size, you’re either going to have to move ALL images surrounding the image you have to update (and obviously then change all background-position properties for the images you’ve moved) or leave a space and put the updated image in a new position in your sprite.

How do you know which images in a sprite are used and which ones are dead? Since your images are referenced by coordinates, this sort of clean up becomes a nightmare and is actually a bit lot of a nightmare to create image sprites in the first place.

The goals of the project are to

  1. Reduce the number of http requests (and their associated header traffic) to the server and hence reduce the time it takes to load all images on a website and bandwidth footprint the site requires
  2. Create a solution that’ll alleviate some of the problems surrounding the creation and use of image sprites
  3. Do something cool

The JSIO project website has a pretty good explanation of how it works so I won’t bore you with the details here. However, as a brief overview, it packages all your image data in data uri format and you reference particular images by their filename rather than their coordinates.

The site actually uses the HTML5 file api to generate your resources file for you, which makes creating and maintaining your JSIO “sprite” really really easy.

I read *somewhere* that data uri encoded images can be up to 1/3 larger than corresponding image files, however with gzip encoding they can be only 0-3% larger (or less). My thesis is that for a site with many small images, JSIO could be more efficient and easier to maintain than having separate files or even an image sprite.

…I’m yet to prove or disprove this and I’ll be conducting some tests whose results I’ll post up here (even if they do prove JSIO to be useless).

Disclaimer: This is the first ever ALPHA release of JSIO – it works on the latest Firefox and Chrome but I haven’t even checked it in IE yet. It probably won’t work in IE yet. Also, the website needs some work for optimal display on mobile devices.

The difference between using single quotes and double quotes as string delimiters in JavaScript/PHP

I like to keep all my string delimiters in languages such as PHP and JavaScript consistent. I consistently use single quotes for a couple of good reasons, so when I encounter someone else’s script that uses double quotes the OCD in me makes me change them all to single quotes…but that is a different problem.

If you’re coming from a language such as C# or Java then note that in PHP and JavaScript there is no such thing as a character datatype – as such, you can use either single or double quotes to delimit strings.

If I could only give you one reason why I consistently use single quotes then I would have to go with this:

If you ever (God forbid) need to write HTML in a string, you don’t need to escape the double quotes around attribute values. Instead of:

    "<div id=\"foo\" class=\"bar\">foobar</div>"

You write:

    '<div id="foo" class="bar">foobar</div>'

…which is lots less characters to type and I’d say more readable. Also, I more frequently use double quotes in my JavaScript/PHP strings than single quotes so it really does make sense.

The other reason is that if you use double quotes, PHP will actually parse the contents of the string to find variables and escape characters (\n, \r, \t etc.) which it’ll replace with the variable value or correct escape character respectively. So for example:

<?php

    $baz = 'bar';
    echo "foo\n$baz";

?>

Will print:

foo
bar

Whereas:

<?php

    $baz = 'bar';
    echo 'foo\n$baz';

?>

Will print:

foo\n$baz

So if you don’t need any of this functionality in your string, you’re making PHP do some extra work for no reason.

jQuery plugin to associate label “for” attribute with form controls that have dynamic id’s

For whatever reason, you can’t associate your labels with your form controls implicitly by wrapping both the label text and the control in a <label> element:

<label>
  Email address: <input type="email" name="email" value="" placeholder="you@example.com"/>
</label>

You’ve had to explicitly state the form control you want the label to be associated with:

<label for="email">Email address:</label>
<input id="email" type="email" name="email" value="" placeholder="you@example.com"/>

…but your framework has other ideas, it decides to commandeer your precious “id” attribute and change it from a simple and beautiful “email” into a junky “dnn_ctr1163_RegistrationForm_email”. *cough* DotNetNuke *cough*, but also *cough* Wicket *cough* and probably a whole load of others.

The problem is now that your label is no longer associated with your form control, and there isn’t a simple fix, like, for example, change the for attribute to read “dnn_ctr1163_RegistrationForm_email”, because the numbers in the id change each time you refresh the page. The ID is dynamic, and you are receiving accessibility black stars.

So, luckily I noticed that often the id will change, but the framework will leave your originally intended id somewhere in there. I’ve written a jQuery plugin to look at label for attributes and try to find the form control you intended to associate it with before your server side framework so rudely changed it.

How to use

  1. Download the plugin and add it to your page
  2. Select the labels you want to re-associate and call the function eg. $(‘label’).fuzzyFor();

TODO

The plugin finds matches by looking for input, select and textarea elements in the document and checking to see if the for attribute in your label element appears in the id attribute of the form control. At the moment if more than one match is found, it just uses the first (which is probably good enough for most). However, it should probably do something a bit more clever and use the form control that is closest to the label (I’m reasoning that you normally put your label’s close to your controls).

Array.toString

I was recently trying to debug some code that returned an array of arrays. In Actionscript and seemingly most (if not all) ECMAScript implementations, when calling toString on an array object it passes back a comma separated list of elements in the array. This is no good if you have nested arrays because:

    [1, 2, 3, [1, 2, 3]].toString();

…returns:

    "1, 2, 3, 1, 2, 3"

So it appears as a flat array, whereas the underlying object is something entirely different. So if you happen to be quickly debugging using trace (ActionScript) or alert (JavaScript) the object can appear to be something it is not.

If you want the Array object to return a string of comma separated elements contained in square braces then run this snippet somewhere before you start creating new Array objects:

    Array.prototype._toString = Array.prototype.toString;
    Array.prototype.toString = function() {return '[' + this._toString() + ']';}

Now:

    [1, 2, 3, [1, 2, 3]].toString();

…returns:

    "[1, 2, 3, [1, 2, 3]]"

Much better!