battling with the back button

Recently, and also a few months back, I had a long drawn battle with the browser back button. There just seems to be something intrinsically broken with the web model using AJAX and that pesky button. In fact, even without AJAX, the back button in combination with form data seems to cause more than enough problems on its own. Consider my latest fight below.

My task was to repopulating a form when the user clicks on the back button. For those not familiar with the problem at hand, when a user clicks on the back button the page displayed is rendered from cache, and no request is made to the server. The actual page displayed when the back button is clicked may be in various states depending on both the browser being used, and the way this page was constructed in the first place, i.e. if it was rendered in stages with AJAX/JavaScript requests or just once when the page was loaded.

A simple, or not so simple, way to repopulate the form is by performing an AJAX call when the DOM loads, and either rendering the part of the page again and sending HTML in the response, or sending the form values back using JSON, etc.

Here I’m going to consider the first of these suggestions, but the problem I faced applies equally to the second (I think!). Let’s suppose that we make a request to the URL https://equivalence.co.uk/Step1/Index and that we are following some kind of wizard where we have “Previous” and “Next” buttons to navigate between the steps. Furthermore, let’s assume that the page rendered by default when accessing Step1/Index contains a form. Now suppose that we click the “Next” button and navigate to our new URL, say https://equivalence.co.uk/Step2/Index, and on this page we decide to hit the back button. As I described previously, on reloading Step1 we make an AJAX call back to the server, and importantly, we send the request to the same URL as the page we are currently on, i.e. Step1/Index.

When receiving this request on the server we check whether it’s an AJAX request or a simple GET then render accordingly. It’s probably reasonable to ask why the hell I was doing this, well if the server received an AJAX request there was no need to render the whole document again as I am only interested in the form element, but on the GET request I wanted to render the whole page.

However, this is where I ran into a little problem. Now suppose that we click the “Next” button again to move to Step2/Index and once again hit the back button. What is displayed?

Well as a surprise to me it was only the form, i.e. the response returned by the AJAX call, not the full page, no HTML head, nothing, just the form. Now that I have seen this behaviour, I totally understand why this is happening; the browser checks for the most up-to-date data sent for this URL, which in my case corresponds the AJAX request when the back button was hit previously. For some reason I just didn’t expect this – incidentally this was the behaviour on Firefox, I’m not sure what happens in the other browsers. As a result, when I was making the AJAX call I had to change it to make the call to “Step1/Index2” instead, now everything worked fine – I think maybe supplying a random get parameter to the original URL may also have worked.

So there we go, that’s it! Exciting post? Maybe not! Hopefully this helps someone though. It’s always something to bear in mind.

PS I’ve ended up with the weirdest problem ever whilst typing this entry in Google Chrome, it’s somehow messed up the keyboard mapping. As an example the top row on a QWERTY keyboard types as “azertyuiop^$” and you have to press shift to get the numbers. Strange.

sticking with what you know

There comes a time in every programmers life when they have to learn new things and step out the box. Yeah it’s difficult, for sure. It’s all too easy to create the latest application in your software empire, using a language you’ve been developing in for the last 10 years. However, the real problem is thinking this is the only choice. When is it time to abandon this certitude?

First, we cover the forced abandonment. This is when you are pushed kicking and screaming into pastures new, whether you like it or not, i.e. the new job. Here, not only is the new language curve ball thrown (viciously), but you also get whole new set of business rules into the bargain. So what do you do? You program the new language like the old one, only translating the syntax in your head. This is not the best way to learn a language though. Why? Well consider those C programmers trying to program imperatively in Java, Java programmers in JavaScript, C++ programmers in Ruby, and so on. When there is a change in paradigm this mapping strategy just doesn’t work – a similar situation exists with languages that contain a more powerful expression set. It also encourages the behaviour where people learning enough to get the job done, without understanding what is really happening, or that there may have been a better way using “unmappable” language’s features. A better approach would be to write something small, and new, that allows you to explore the language’s features. I’m sure most people can think of something they could write. Furthermore, if you can make it useful to other people, or even your new employer, then everyone’s a winner! This is something I touched on before.

For many people though, this is the only time they will ever consider abandoning. This is sad, and a poor characteristic in a programmer. And to be honest, I just don’t understand it. That’s not to say that I don’t accept that people just do programming as a job, then go home and don’t think about it. However, it’s like most things in life, it’s nice to progress?

As a programmer there will also be other signs that the tide is turning, and you don’t have to be too alert to spot these. Previously I wrote “Perl is Dead, Long Live…Perl?” and being a big Perl fan it was sad to see the language apparently dying, so I know what it’s like. Some signs to look out for may be:

  • the language features are not moving on (Java watch your back) – the people who created it no longer care,
  • the community surrounding the language is dwindling – the people who use it no longer care,
  • there is little in the way of choice when selecting libraries/frameworks – the experts have fled,
  • other programmers have never heard of it – there is no buzz,
  • jobs using it are few and far between – businesses have given up on it, the death kneel.

However, this is all not to say that you give up on your language just because it’s no longer cool – popularity is by no means a great indicator that something will suit your needs. It need not be the case that you give up on your language of choice, instead it could be that you contribute and drag the language forward. But be careful with this one.

Finally, any decent employer will want to see that you are continually developing your skill set – their business needs are continually evolving, so why aren’t you? You are much more likely to land a better job if you contribute to your own education in some way. It looks good and it’s also something to talk about.

So go out and learn something new today, and stop sticking with what you know.

strong coupling and web development

We are all well aware of the dangers of strong coupling: for me, the most dangerous being the increased maintenance costs in such a system. Much has been discussed about coupling and measures such as dependency injection are used to help control it.

However, as far as a Google search leads me to believe, but I didn’t search too hard, not much has been said about the strong coupling that can exist between HTML, CSS, and JavaScript files. Maybe I’m doing something wrong, or at least something different, from others but many times in recent weeks I have found that the dependencies between these files can be rather tight and restrictive.

To understand what I’m talking about, let’s take a look at an example. Consider the following snippets of an HTML, CSS, and JavaScript files respectively:

1
2
3
4
<div id="main_wrapper">
    <h2>Header</h2>
    <div id="content"></div>
</div>
1
2
3
#main_wrapper {
    color: #FFFFFF
}
1
$('#main_wrapper').attr('color', '#000000');

As you can see the id is referenced in at least three different places. Well so what?

The problem, as I see it, comes from the fact that it is more than likely these files will be maintained by different people. For example, a designer is likely to maintain the HTML and CSS files and a developer the JavaScript file. In the days before JavaScript proliferation, this maybe wasn’t such a problem. However, with the rise of jQuery and its awesomeness the landscape has changed a little.

In fact, jQuery actually compounds the problem, as we have all become accustomed to seeing JavaScript code littered with things like $('#main_wrapper'), i.e. CSS selectors are referenced throughout the code base. What this means is that when the designer changes the structure of the HTML file, or the class names and ids, it can have unexpected side effects.

The easy (part) solution to all this is that when you create ids and classes you never change/remove them or their container – or at least you never change them without searching globally rather than just locally. I’m not sure how restrictive this is though, maybe those with far more experience of this than I do can offer up some more constructive thoughts? Are designers are just not used to such constraints? I dunno?

To me it just seems like a hassle having to keep track of selectors, ids, and classes in so many different places. It seems to go against the spirit of good programmer where we try to localised any side effects when changes are made. With the above way of working this doesn’t seem possible – and combined with the divided level of responsibility between designers and developers, I imagine this causes an increase in the number of bugs and also in the cost of maintenance.

Maybe others don’t see this as an issue at all? Maybe I’m doing designers around the world a disservice? You decide.

At the moment I can’t offer up any better solutions, as I have not really thought about it too much yet. When I do though, I’ll be sure to report back 😀

iterative development

We’ve all had it drilled down our throats that development should be completed in short-sharp iterations. “Release early and release often” – no agile developer gets up in the morning without repeating this mantra to themselves before they reach the sink. However, surely it’s important to realise the difference between “Release early and release often” and “Release utter shit early and release utter shit often”.

Who really wants to use an application/toolkit/library that has so many bugs in it that the user experience is dreadful? Surely users would rather wait a few more weeks for something that is, in a sense, polished? I mean we’re not talking Microsoft Vista style release cycles here, but quality control consisting of a little more than running a set of unit tests would be nice.

So what has prompted this minor rant? Well Firebug unfortunately. I hate to criticise it because it’s free but the bugs I find in it are getting worse and worse. The most recent one being that the continue button no longer works in the latest release (1.4.0b10). Sigh. However, open source or not, my feeling is that if you choose to do something then do it properly or not at all.

Anyway. Regardless of the product, it surely makes more sense to sacrifice your release schedule a little for some real testing and bug fixing? For commercial products a bad user experience is going to make a sale difficult both now and in the future. Being first to market is one thing, but it’s far from being the only (or even main) contributing factor to a products success – Google and Facebook being good examples of this.

So is it possible just to have a little common sense about all this and maybe restate the mantra as “Release quality early, release quality often”. It can’t be that hard, right?

JavaScript media player

Download JavaScript Media PlayerA while back I was impressed to see the Yahoo Media Player, which can be used to stream mp3s on a website. It appeared on the face of it to be a JavaScript only browser media player, which seemed not only impressive, but impossible. As it turned out, the media player actually used flash underneath the hood by making a series of API calls without the need for the typical flash UI.

Being suitably impressed I decided to write my own – I wanted several distinct features like a playlist and a custom look. I then found an astonishing good JavaScript API that interfaced to the audio features in Flash. This library was called SoundManager2, check it out, it’s great. SoundManager does provide some neat demo applications, but nothing that matched my needs – incidentally the demos may be far better now as I wrote this code almost a year ago.

So what was I looking to achieve with this:

  1. I wanted to queue tracks in a playlist;
  2. The order of the playlist must be dynamic, i.e. you can drag and drop the tracks to change their order;
  3. Adding the media player to a website is as easy as adding a div with a specific id attribute;
  4. Adding items to a playlist must be as simple as including an anchor tag with a specific CSS class;
  5. The colours, dimensions, and images should be easily overridable but also have sensible defaults;
  6. The path to the library should be configurable in some manner.

So what did this turn out like? Well you can see it in action on www.feellikefalling.com. I encourage you to check it out to see things like the play list drag and drop etc in action. Update: I have embedded the player here so that you don’t need to navigate away if you don’t want to.

So if you want to include this on your website how to you do it? It’s pretty easy – you don’t need to be a web developer! First you need to download all the required files by clicking the big button above or here, extract the files, and then upload the these files to your web server. The HTML required to embed the player is minimal and is show below:

1
2
3
4
5
6
7
8
9
10
11
12
<div id="myplayer"> 
  <a class="myplayer_mp3" href="song1.mp3" 
     title = "Feel Like Falling - Can't Rock With The Kids">
      <span class="myplayer_artist">Feel Like Falling</span> - 
      <span class="myplayer_song">Can't Rock With The Kids</span>
  </a>
  <a class="myplayer_mp3" href="song2.mp3"
     title = "Feel Like Falling - Purple T">
      <span class="myplayer_artist">Feel Like Falling</span> -
      <span class="myplayer_song">Purple T</span>
  </a>
</div>

To include the website media player in the page you simply add a div element with id myplayer. Then to add an mp3 to the playlist you create an anchor (a) tag with class myplayer_mp3. To include a tooltip for the song you simply add a title attribute to the a element. So what we are doing is creating a playlist from a series of urls specified in the a tags, it’s as simple as that.

In order to get all this to work you need to include the following in your document header:

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
<link rel="stylesheet" type="text/css" href="js/myplayer/player.css">
 
<!--You must specify the location, relative to this file, where
    the myplayer source can be found. This allows it to set up
    some things automatically for you -->
<script type="text/javascript" charset="utf-8">
  var _MyPlayerLocation_ = "js/myplayer";
 </script>
 
<!-- It uses jQuery so load the main jQuery library however 
     you wish in this case I'm using Google to host it -->
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
  google.load("jquery", "1.3.2");
 </script>
 
<!--The rest are JavaScript file that are required by the media
    player and should be included in the order specified - they 
    are all contained in the downloadable zip file. All you have 
    to do is make sure you have specified the correct path
    relative to this file -->
 <script type="text/javascript"
          src="js/myplayer/jquery/jquery-ui-custom.min.js"></script>
 <script type="text/javascript"
          src="js/myplayer/jquery/jquery.tooltip.js"></script>        
 <script type="text/javascript"
          src="js/myplayer/soundmanager/soundmanager2-min.js"></script>
 <script type="text/javascript"
          src="js/myplayer/utils.js"></script>
 <script type="text/javascript"
          src="js/myplayer/myplayer.min.js"></script>

Instead of explaining all of the above I suggest you just take a look at the inline comments. There is also a sample HTML file in the downloadable zip containing full working example – apart from the actual mp3 sound files.

You can also customise the player visually with relative ease. The colour scheme can be changed by simply overriding the default CSS styles for the player. For example, consider the following screenshot:

Customised Media Player

Here the volume bars, the play timer, the currently playing song background, and main background colour have all been changed. The code below shows the CSS elements that had to be changed/created to achieve this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
div#myplayer { background-color: #696969; height: 25em; }
 
#myplayer_playlist_container { height: 20em; }
 
div#myplayer_playing_timer { background-color: #6D0D33; }
 
div.myplayer_strip_skin_on { background-color: #6D0D33; }
 
#myplayer_playlist li { background-color: #929292; color: #FFFFFF; }
 
a.myplayer_mp3 { color: #000000;	}
 
#myplayer_playlist li.ui-selected { background-color: #6D0D33; }
 
#myplayer_playlist li.ui-selected a { color: #FFFFFF; }

Hopefully the method of skinning the player, as shown above, is straightforward to understand, it’s just basic CSS. Obviously just about anything can be customised through the use of CSS, and I suggest taking a look at the generated HTML to identify the appropriate ids and classes – you can use firebug HTML explorer with Firefox (or the equivalent in IE, Chrome, Safari, etc). In fact, the HTML generated can also be modified easily – take a look at the myplayer_snippets.js to do this. Be aware though that some of the elements generated are essential to the working of the application though.

For those more artistically inclined than me feel free to give it a sweeping new skin – in the colours of the site I linked to so that I can get the benefits 😉

It goes without saying there will be bugs! If you find any, either leave a comment or better still email me – my address can be found in the about section of this site.

So feel free to add the webpage media player to your site! Enjoy.Download JavaScript Media Player

is open-source software worth it

I’ve been having some real problems with FireBug recently – essentially it has made itself utterly useless. Why? Well when I set a breakpoint within FireBug and that breakpoint is reached, the code window does not scroll to the breakpoint. I then have to drag the scroll bar down to the breakpoint, then when I press F10 to perform a step over, the code window resets itself to the top. As you can imagine this get rather annoying after a while, especially with large JavaScript files.

As a result of these misgivings I have found myself using the IE8 developer tools – which are actually quite good, though FireBug, when working, is better.

Luckily the project that I’m working on is not exactly critical, though the quicker I get finished it the better. However, if I was working on something that was going to generate me $$$$$$, I’d hope to god that I wouldn’t have to waste so much time with the debugger. With this in mind, and with the mindset of “You are a dumb ass if you fail to utilise open-source software” prevalent in our industry, it raises the question as to the limits of open-source software.

If the software that you are developing is largely based on open-source/free software, and this software sells for hundreds of thousands do you really want to be using libraries that have no real service-level agreement? For example, let’s assume that your software sells for $200,000. Then it’s safe to say that your customers will be expecting some pretty good service for that kind of money. Suppose a bug is found in some third-party open-source library that is used in your product. So you have two options: 1) you ask the community to fix the bug or 2) you fix the bug yourself. Are any of these really a satisfactory solution? I don’t think so.

Consider option 1. Suppose that the project stagnates or your bug is just not an issue for the community, then it may take some time to get this bug fixed (or they may not fix it at all). But you need this bug fixed yesterday! People tell you “Oh there is always someone in the community willing to help”. Nonsense. There are no guarantees and this is exactly what a professional organisation needs. A bank, telecom company, utilities company and so on are not going to give a shit that you can’t get it fixed soon, they will just move their business elsewhere. This is the reality of the situation, and if you are moving a core part of your business out to open-source software and charging a small fortune for your software, I’m pretty sure this is going to come back and bite you. Open-source software proponents can scream until they are blue in the face that this will not happen, but it might, and that’s all that matters.

So if option 1 cannot save you then your left with option 2. Well first, it’s easy to say that you just get the source and edit it yourself, but the fact of the matter is that it takes quite some time to be comfortable with a large code base. In particular, to be comfortable with the fact that making changes in one place doesn’t cause problems elsewhere. OK, unit tests help, but there are no guarantees. Maybe you could be involved in the maintanence of the open-source software on a regular basis to ensure that your team has built up a familiarity with the code. Maybe even developing new features etc. That sounds like a great idea. Until your competitor comes along and uses all these lovely features that you have so kindly developed for them! Then how much of a fool do you look.

The fact of the matter is that if you write the code, then you have more control over it, and this eliminates any dependencies you may have on outside parties. The more you charge for your software, the tighter your service level agreements are, and the more third-party libraries define the uniqueness of your product, the more important this becomes.

This is not to say that we should all go out and write our own compilers, IDEs, and various other things. It’s just a matter about being sensible about what you use.

javascript done right

Well its been a while since I last used JavaScript, but I’m back at it with a bang. However, it would appear that people are still writing JavaScript as awful as ever. I’m not claiming to be a JavaScript expert but I see people do things in JavaScript that they wouldn’t even consider doing in languages like C++, C#, Java, and so on. Why is this the case? I can only presume that they don’t know any better. With this in mind, let’s take look a few not so nice bits of JavaScript namely global variables and scope, and see how we can make this situation better.

With C (and C++) we have global variables, that is, a variable which is available at each and every scope of your program. Why is this bad? Well due to the fact that this variable does not have any sense of locality, it can be changed anywhere in your code. Thus, there can be a large number of dependencies on such a variable – something which all good developers know is bad. This can also lead to name clashes resulting in unpredictable behaviour. So why is JavaScript so bad? Well it bases its programming model on global variables. Damn.

So what are the problems with scope in JavaScript? Well JavaScript does not have block scope – this may appear odd to those used to C-style syntax. What does this actually mean and what’s the problem with this? Well I’ll steal an example from the book Javascript – The Good Bits by Douglas Crockford where you can see how confusing this can be:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var foo = function () {
    var a = 3, b = 5;
 
    var bar = function () {
        var b = 7, c = 11;
 
        // At this point, a is 3, b is 7, and c is 11
        a += b + c;
 
        // At this point, a is 21, b is 7, and c is 11
    };
 
    // At this point, a is 3, b is 5, and c is not defined
    bar();
 
    // At this point, a is 21, b is 5
};

However, despite these nuances in the JavaScript language, with a little thought and engineering we can get round this.

First, let me say that JavaScript really is a great language, don’t underestimate it. Many languages have bad features, it does not mean that you have to use them.

Now getting round the global variable problem is pretty simple, we create a global object and place all our JavaScript code within this object. The code below shows an example of how to do this.

1
2
3
4
5
6
var APPLICATION_NAMESPACE = {};
 
APPLICATION_NAMESPACE.my_object = {
     my_name : "Name",
     my_function : function () { alert("ALERT"); } 
}

This style of coding in JavaScript should be familiar to users of jQuery – instead of APPLICATION_NAMESPACE you use $ or jQuery. There we have it, this gives us a nice way to get round those pesky global variables.

Now, if like me, you are used to a more object-oriented (OO) style of software development then JavaScript can appear a little awkward at first. With no classes and traditional inheritance the typical OO developer is left wondering what to do. This need not be the case.

One development pattern that comes to the rescue for OO developers has been proposed, once again, by Douglas Crockford and is known as the module pattern. So how can we use it? Well say we want to create a “class” Person that has a “public” method fullname which uses a “private” method concat, this is represented using the module pattern as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function Person () {
    function concat() {
        return firstname + surname;
    }
 
    return {
        fullname: function(firstname, surname) {
            return concat(firstname, surname);
        }
   }
}
 
// To use Person we do the following
var person = new Person();
var name = person.fullname("Davie", "Jones");

As you can see this allows for sensible scoping of variables and functions, and at the same time makes a JavaScript objects look like classes. Also, this method of developing objects in JavaScript just about eliminates the need for global objects.

I’m a little hesitant to use JavaScript as a fully blown OO language – as this is not how it was intended. Instead we should embrace the alternative style of programming that JavaScript gives us. After all, if you were using a functional language like Haskell, F#, Scala and so on, you wouldn’t expect to write code as you would in a language that supports the typical OO constructs.

The fact is that JavaScript is here to stay for a long long time, so you may as well learn to love it 😀 .

7 ways to write beautiful code

I’ve noticed that the developer and designer community appear to be obsessed with lists. Is this for a reason that I have somehow missed? For example, over at dZone, 2 out of the top 3 most popular articles are lists: 15 CSS Tricks That Must be Learned and 10 Dirty Little Web Development Tricks – incidentally I liked both articles so I seem to have this obsession myself. OK this is not that many but hey I’ve seen loads of lists elsewhere. Anyway, I thought I would embrace this culture to feed my own addiction and I have detailed 7 (I was only going to do 5, and 6 was out as it’s not prime 😉 ) ways to write beautiful code.

First things first here, I’m talking about pure aesthetics, nothing else. As I have said previously, good code starts by being something other people find easy to read. In fact, Jeff Attwood had a blog post comparing coding to writing citing several sources. I urge you to take a look.

Anyway on to my list.

  1. Return from if statements as quickly as possible.

    For example, consider the following JavaScript function, this just looks horrific:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    
    function findShape(flags, point, attribute, list) {
        if(!findShapePoints(flags, point, attribute)) {
            if(!doFindShapePoints(flags, point, attribute)) {
                if(!findInShape(flags, point, attribute)) {
                    if(!findFromGuide(flags,point) {
                        if(list.count() > 0 && flags == 1) {
                              doSomething();
                        }
                    }
                }
           }
        }   
     }

    Instead we can change the above to the following:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    
    function findShape(flags, point, attribute, list) {
        if(findShapePoints(flags, point, attribute)) {
            return;
        }
     
        if(doFindShapePoints(flags, point, attribute)) {
            return;
        }
     
        if(findInShape(flags, point, attribute)) { 
            return;
        }
     
        if(findFromGuide(flags,point) {
            return;
        }
     
        if (!(list.count() > 0 && flags == 1)) {
            return;
        }
     
        doSomething();
     
    }

    You probably wouldn’t even want a function like the second one, too much going on (see point 7), but it illustrates exiting as soon as you can from an if statement. The same can be said about avoiding unnecessary else statements.

  2. Don’t use an if statement when all you simply want to do is return the boolean from the condition of the if.

    Once again an example will better illustrate:

    1
    2
    3
    4
    5
    6
    7
    8
    
    function isStringEmpty(str){
        if(str === "") { 
            return true;
        }
        else {
            return false;
        }
    }

    Just remove the if statement completely:

    1
    2
    3
    
    function isStringEmpty(str){
        return (str === "");
    }
  3. Please use whitespace it’s free!

    You wouldn’t believe the amount of people that just don’t use whitespace – you would think there was a tax associated with using it. Again another example and I hesitate to say this but this is from real live code (as was the first example), all I have done is change the programming language and some function names – to protect the guilty:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    
    function getSomeAngle() {
        // Some code here then
        radAngle1 = Math.atan(slope(center, point1));
        radAngle2 = Math.atan(slope(center, point2));
        firstAngle = getStartAngle(radAngle1, point1, center);
        secondAngle = getStartAngle(radAngle2, point2, center);
        radAngle1 = degreesToRadians(firstAngle);
        radAngle2 = degreesToRadians(secondAngle);
        baseRadius = distance(point, center);
        radius = baseRadius + (lines * y);
        p1["x"] = roundValue(radius * Math.cos(radAngle1) + center["x"]);
        p1["y"] = roundValue(radius * Math.sin(radAngle1) + center["y"]);
        pt2["x"] = roundValue(radius * Math.cos(radAngle2) + center["y"]);
        pt2["y"] = roundValue(radius * Math.sin(radAngle2) + center["y");
        // Now some more code
    }

    I mean I won’t bother putting an example of how it should be – it should just be sooo bloody obvious. That said, I see code like this ALL the time and so certain people do not find it that easy to judge how to use whitespace. Screw it, for them I will inject some whitespace into the example and it’s shown below.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    
    function getSomeAngle() {
        // Some code here then
        radAngle1 = Math.atan(slope(center, point1));
        radAngle2 = Math.atan(slope(center, point2));
     
        firstAngle = getStartAngle(radAngle1, point1, center);
        secondAngle = getStartAngle(radAngle2, point2, center);
     
        radAngle1 = degreesToRadians(firstAngle);
        radAngle2 = degreesToRadians(secondAngle);
     
        baseRadius = distance(point, center);
        radius = baseRadius + (lines * y);
     
        p1["x"] = roundValue(radius * Math.cos(radAngle1) + center["x"]);
        p1["y"] = roundValue(radius * Math.sin(radAngle1) + center["y"]);
     
        pt2["x"] = roundValue(radius * Math.cos(radAngle2) + center["y"]);
        pt2["y"] = roundValue(radius * Math.sin(radAngle2) + center["y");
        // Now some more code
    }
  4. Don’t have useless comments:

    This one can get quite irritating. Don’t point out the obvious in comments. In the example below everyone can see that we’re getting the students id, there is no need to point it out.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    
    function existsStudent(id, list) {
        for(i = 0; i < list.length; i++) {
           student = list[i];
     
           // Get the student's id
           thisId = student.getId();
     
           if(thisId === id) {
               return true;
           }
        }
        return false;   
    }
  5. Don’t leave code that has been commented out in the source file, delete it.

    If you are using version control, which hopefully you are – if not why not! – then you can always get that code back easily by reverting to a previous version. There is nothing more off putting when looking through code and seeing a large commented out block of code. Something like below or even a large comment block within a function itself.

    1
    2
    3
    4
    5
    6
    
    //function thisReallyHandyFunction() {
    //      someMagic();
    //      someMoreMagic();
    //      magicNumber = evenMoreMagic();
    //      return magicNumber;
    //}
  6. Don’t have overly long lines.

    There is nothing worse than when you look at code that has lines that go on forever – especially with sample code on the internet. The number of times I see this and go ahhhhhhhhhh (I’ll switch to Java for this, as generics makes this particularly easy to do):

    1
    2
    3
    4
    5
    6
    
    public static EnumMap<Category, IntPair> getGroupCategoryDistribution(EnumMap<Category, Integer> sizes, int groups) {
            EnumMap<Category, IntPair> categoryGroupCounts = new EnumMap<Category,IntPair>(Category.class);
     
            for(Category cat : Category.values()) {
                categoryGroupCounts.put(cat, getCategoryDistribution(sizes.get(cat), groups));
            }

    I’m not suggesting the 70 characters width that you had to stick to on old Unix terminals but a sensible limit like say 120 characters makes things a little easier. Obviously if you are putting sample code on the internet and you have it within a fixed width container, make it easier for people to read by actually having it fit in the container.

  7. Don’t have too many lines within a function/method.

    Believe it or not a few years ago now an old work colleague exclaimed that Visual C++ was “shit” as it didn’t allow you to have a method with more than 10,000 lines. I kid you not – well ok I can’t remember the exact number of lines but it was huge. I still see this time and time again where a function/method is at least 50 lines long. Can anyone tell me this is easy to follow? Not only that but it normally forms part of an if statement that you can never find the enclosing block because you are scrolling. To me anything over 30-35 lines is pretty hard to follow and requires scrolling. My recommendation is if it’s more than 10-15 lines consider splitting it up.

This is by no means an exhaustive list and I could have gone on longer – in fact my abolish the switch statement motto would have been number 8 if I had not already mentioned it before. However, it has to end somewhere but feel free to state your own annoyances and maybe I can update the post with some more.

Over and out.

json is where it’s at

Well people I must say that I have come to LOVE JSON quite a bit in the last few months. Having used in on several projects both in work and in play.

However, not so long ago, I used XML for my configuration and data passing needs. I have always pretty much hated (YES! I said it in public) XML. Everything you do with it just seems loooooooong and verbose; a bit like the applications that (over)use it.

I mean we could just abandon structure altogether in a document and save time by not tagging anything, but where does that get us? Nowhere I imagine. It’s nice to have structure, just not an overwhelming amount that XML provides, especially when you only need it for are some simple config files, or sending messages between processes. XML is especially wasteful of space when you have a rather large file with a structure like below, multiplied by 10,000:

    <person>
       <id>1</id>
       <pref>8;3;4;5;6;7;9;10;11;13;17;18;19</pref>
    </person>

The above is data basically representing a list of choices, in strict order, for a person with id 1. So, person 1 prefers person 8 to person 3, person 3 to person 4 etc. To me it was better than what people used before XML, and let me tell you is still used now, which is:

1 3 4 5 6 7 9 10 11 13 17 18 19

Yes this is simple, clean and has no “spare” characters being used. However, when you have a problem with person number 7868, it makes debugging a little harder. It also makes changing person 7868’s prferences also very difficult.

With JSON this can be done as follows:

{ 'id' : 1,
  'prefs' : [1,3,4,5,6,7,9,10,11,13,17,18,19]}

It just sits as a very nice compromise between the latter schools of thought. I realise that this may seem very specific but I’m certain that it’s true in general. Not only is it less verbose, it is also easy to integrate with JavaScript on the client side of any web app, and for me with a little nurturing JavaScript is gonna be where it is ALL at it a few years time.

So the next time you go to use XML in a project, have a think first and see if JSON is your new friend.

programmer rehab

Faced with the task of learning a new programming language (and its associated libraries) I was left considering what is the best way to do this effectively. I will now describe what I do, and by no means am I advocating its use, be aware of the hidden dangers that lie with it.

My first port of call is normally to try and see if some book on Amazon is the overwhelming favourite of the masses and purchase it. I must admit though, I often get the book, flick through it, and then probably ignore just about everything in it. I do however normally remember the name of the book and the author and when someone asks me if there is a book I recommend I spout this information to them. So the moral of this is probably never to ask me to recommend a book as I’m probably grossly misinformed about what is actually in it.

Anyway, in the first week of learning the language I will try to map the syntax of the language to concepts I know, i.e. object-orientation. This probably presents the first problem: what if the language is not really object-oriented? My solution, make it object-oriented 🙂 This can prove tiresome in certain languages, and JavaScript in particular. However I’m not one for letting this type of hurdle get in the way, and tend to find a way to do this (with JavaScript this was the module pattern described by Douglas Crockford). By the second week I’m normally getting pissed off with my lack of understanding of the language’s features. I think this in part stems from the fact that my style of coding appears to be a copy-paste based system. What I mean by this is that quite often at the start I won’t even bother learning how to say define a class – I will find it out once then just copy-paste the class definition in from another class and change the name. A similar process is then used for other language features (I must point out I’m not copy-pasting the code itself though, that’s just waaay too 80’s). So those first couple of classes and library calls can be like kicking smoking the crack pipe.

After this initial push though, it tends to get easier, I replace the crack induced cold turkey with a slightly more sociable nicotine based habit, but experience constant irritation at the need to stand out in the cold street whenever I want to spark up in public. At this stage I try to abstract most things away from the language itself and think more about how I can isolate change. In other words I tend to have the thought process where I ask myself, if someone asked me to change a requirement, how can I do it with just a change to one line; oh and preferably that one line I would have to change is at the top of the file so I don’t have to search through everything to find it. My motto is that not everyone cares enough to want to learn how something works and is happy if the process is simple and easy. Me, I prefer to waste a mountain of time trying to figure out every detail of how the code fits together – I really need to give up that pursuit, rehab or something. So at this point I start to trace into every language feature, not happy with it just working – tantamount to starting chain smoking. If I get through this stage then I will normally stick with the language, many however have fallen by the wayside after two weeks. More so learning specific frameworks though, as you start thinking “God I could do this far easier if I was writing ALL the code myself”. Remember if you get these thoughts they are normally bullshit though, try to ignore them, as you ARE wrong, you just don’t know it. It’s your mind trying to trick you out of a little hard work. All you will be is a hopeless quiter!

So only after I’ve kicked the crack pipe by weeding myself on to ciggies, and then developed a massive chain smoking habit, do I get the moment of enlightenment where I dump the ciggies and tag myself clean of any irritants (well apart from all those people who tell you that you have learned the wrong language, who all should go get a life). At this point I still occasionally use my copy-paste system described above but it’s becoming easier.

As I said at the beginning of this post I’m not sure this is the best way to go about this process. The main problem that I see is that I don’t learn all the language specific features (maybe this is a good thing). In most languages I work with a standard set of ideas that I apply to the specific language. This always leaves me thinking I could get more out of the language if I only pushed the boundaries a little further. For example, I always think that I’m not quite getting as much out of things like closures, lamdas, etc. I use these things but the way people rave about them I feel there must be more to it.

So that’s it. It usually takes me about a month or so to get comfortable with the language. I then use the language exclusively for around six months and then, for whatever reason, have to shift back to an old favourite which I have forgot how to use. So I dust down the crack pipe and seek out the Rizlas and start all over again……