js_include_colour

Coding Standards – any standard you like

We (those who develop software) still argue over coding standards. I do not refer to meaningful discussions over clarity, readability or group/project management. I mean crazy, ranting and aggressive behaviour towards one another over a ‘trivial’ matter.

Before anyone jumps on my face for using the word ‘trivial’, I offer the following advice:

  • If you work at a place with a compelling reason to adopt a style, adopt it and join in on constructive discussions about its use at the appropriate time.
  • If you have a personal preference, then apply it consistently and bask in the loveliness of your own code.

I do not think code standards are trivial and pointless. I think they are important and create clarity. I think arguing about code standards is unimportant. Actually, I think arguing about code standards is more than unimportant, I think it can be destructive for communities in general. It really does not matter what the requirements are, we have programs to format source code at the speed of a key stroke.

PHP, for example, has a number of standards to consider:

That list is not exhaustive, there are many other code standards to consider and they are usually related to various application frameworks. Big choices, big decisions – so big that I can configure my IDE of choice (PhpStorm) to convert my source code to any of them, almost instantly. I can also configure hooks to format code according to a project specifications, which can even be done automatically before commits. Unless you are pair-programming and decide on a mutually acceptable standard, code in whatever standard you like and simply convert it for your needs.

Why argue? Get along with each other and create software instead; you might even catch yourself smiling more!

A Plea for Help

I will soon be talking in schools in my role as a STEM Ambassador and hope some of you might help me with an endeavour. With the introduction of a new computing curriculum in schools, I will be talking to school pupils about computing in the wide world and what an education in computing might lead to. I am not ‘selling’ computing over other subjects, I am letting people know about the opportunities that computing can lead to.

One thing I would really like to do is make a video, because listening to a myriad of lovely, interesting people will be even better than just me, talking.

Interested

I hope you’re interested. If you are, what follows is a little more detail on how you can help turn my presentation into something special.

Using a web cam, phone or other video recording device (a steady one, if you can, maybe a tripod); make a short (30 seconds to 2 minutes) video introduction of (pick any of these you like):

  • Your name, where you’re from and what you do.
  • How you know me, or met me, or even just your Bacon number.
  • Why you like (love/get fanatical/are inspired by) computing.
  • How you learned or studied computing, and what discipline you chose.
  • How you use computing in the things you do every day.
  • What you hope to do with computing in the future.
  • Why you would love to be studying computing for the first time, today.

If you decide to help me out, please leave a comment and I will organise collection and answer any questions you might have. Please keep it school safe! I don’t want to edit your message into oblivion to avoid being banned from schools. If you’re a wizard at video editing and can make an extra special job of it, please do so. I will be learning video editing as I go a long.

I volunteer my time to STEM activities, so I do not have a budget for this activity. I will be relying on your generosity and your time – both highly valued. I will need your permission to use the videos for the purpose of inspiring the new computing generation. If you wish me to follow a specific license, please tell me.

Alan Turing – Pardon Me?

In what way does it make sense for the state to forgive Alan Turing for…well, being himself? A summary from BBC News:

Computer pioneer and codebreaker Alan Turing has been given a posthumous royal pardon.

It addresses his 1952 conviction for homosexuality for which he was punished by being chemically castrated.

The conviction meant he lost his security clearance and had to stop the code-cracking work that had proved vital to the Allies in World War Two.

The pardon was granted under the Royal Prerogative of Mercy after a request by Justice Minister Chris Grayling.

It would seem appropriate for the state to apologise for its past actions and recognise that this is not a good way to treat other people. Making a request for the state to forgive him posthumously seems callous.

I agree with the sentiment, and by today’s standard it would seem abhorrent to treat a homosexual, or anyone else, in the way Alan Turing was treated. However, at the time he did break the law (however absurd it seems now). I can only imagine in 1952 that people saw appealing to law congruent with appealing to morality. I guess that might still be true today. Our law changes, of course, and I prefer that it does when it makes sense to do so. We must recognise the previous state of affairs and be responsible, at least in some measure, for how those decisions might have affected others. Instead of forgiving him, how about we forgive ourselves and work towards this never happening again?

As an admirer of Alan Turing’s work, it is easy to get caught up with him and his contribution to science, but I think it is a distraction in this case.

He should not get a pardon, or an apology, or an overturned sentence for being an extraordinary academic (he was) or someone who took part in crucial work for the government during World War II (which he did). It’s incredible that Turing managed to achieve any of his potential given the time he lived in. An individual pardon addresses none of the concerns of those in a similar situation without the privilege of being an internationally recognised, brilliantly keen mind. Most people are not extraordinary academics and did not do important code breaking work during World War II, but I imagine any ‘outlaws’ were caught and convicted in much the same way as Turing. While I appreciate the message that I think Ed Miliband is trying to convey, I think it misses the mark. The implication being homosexuals that were not extraordinary academics and WW2 code breakers somehow still deserve it – they were not redeemed by their extraordinary brilliance! Can we just say sorry, at least, without caveats, to everyone that had to deal with this?

When laws exist that make it illegal to be yourself, when you do no harm to others, we know that is wrong. Let’s not come off like callous idiots after the fact by forgiving someone (anyone) for the trouble of going through it. We can get on with honouring Alan Turing while we are at it.

Launch Network Utility under Mavericks

Mavericks Network Utility

I thought it may be useful to post the location change of Network Utility in OS X Mavericks. I know I find it useful. I do not know why it moved, but it has.

Previously:

/Applications/Utilities

Now:

/System/Library/CoreServices

Alternatively, you can launch it from the System Information menu, under ‘Window’ (see screenshot).

Launch Network Utility under Mavericks
Launch Network Utility from the Window menu of the System Information application.
Camera Photo of Brooklyn Beta 2013 Main Event.

Brooklyn Beta 2013

I have yet to fully ‘come-down’ from Brooklyn Beta. The come-down started the moment I walked away and it was intense. I had just experienced three days of cerebral stimulation and energising company. Walking to High Street station was ‘cold-turkey’, sobering and sombre. The sombre mood ebbed as the A-train took me North towards 185th Street. I felt privileged, energised and optimistic. I have a lot to consider. Enough about me, for now. What about Brooklyn Beta?

A Conference, Literally

When I think of industry conferences, I am often reminded of commercials and big unveilings of things you sort of know about already. Brooklyn Beta is a conference, the way a conference should be done. Brooklyn Beta brings many creative and technical individuals together in a friendly and a surprisingly, given 1300+ attendees, intimate atmosphere. Personally, I wanted to spend some time with some top designers and get a feel for the design process. I was not disappointed, and I met a wider range of web types too!

The major themes I gleaned from the event:

  • Platforms make for progress
  • Make something you love
  • Create more value than you take
  • Work hard, be nice
  • Use the web to get people off the web

I will not review the talks because others have already done so, particularly in the form of sketch notes. Check out @evalottchen‘s Flickr and Elyse Viotto‘s Blog - particularly for the beautiful and practical sketch notes of the event (I am envious).

The setting for Brooklyn Beta was the Duggal Greenhouse, Brooklyn Navy Yard, which is a grand edifice, sporting a spectacular view of the Williamsburg Bridge (inadequately captured by my phone).

View of the Williamsburg Bridge from the Duggal Navy Yard, Brooklyn.
View of the Williamsburg Bridge from the Duggal Navy Yard, Brooklyn.

The Invisible Dog

I was privileged to attend a series of talks and activities over the Wednesday and Thursday prior to the main event. The Invisible Dog Art Centre is located in Brooklyn, New York. A wonderful little venue that lends itself well to the Beta crowd. There was an art exhibition on display during the event. Approximately 300 people attended the art house and were treated to a variety of talks, demonstrations and local cuisine. All this against the back drop of Brooklyn, in an area that appears to be going through a renaissance. The neighbourhood is a friendly and vibrant place with oodles of character and charm. Brooklyn is a wonderful place to walk. Street walking with a ‘coffee-to-go’ is a personal favourite.

There were a number of things to discuss, some of which I am honour bound to not discuss (love the term FriendDA). The highlights for me were David Marquet‘s talk on leadership, Cloud Typography by H&FJ and a visit from Code Club co-founder, Clare Sutcliffe. A real treat for me at The Invisible Dog sessions were the generous break times, including coffee, with ample time to talk with other attendees.

What’s Next?

There’s a lot for me to take onboard, a lot of concepts and practices to think about. I gained many insights into areas of the industry, craft and practice that I can take with me into new projects. Personally, I’m going to start with the following:

  • Change working environments as explained by David Marquet.
  • Practice sketching for the purpose of note taking – this will be a huge challenge for me.
  • Tackle my code clubs with renewed vigour, concentrate on enabling the material resources.
  • Consider design workflow and integration into current and future software development projects.

If you’re a developer, designer or other form of web professional – visit Brooklyn Beta! To everyone with whom I shared some time and a drink, thank you!

Camera Photo of Brooklyn Beta 2013 Main Event.
Camera Photo of Brooklyn Beta 2013 Main Event.
js_include_colour

JavaScript Include, Part 3

In this third and (as seems most likely at the moment) final article about developing a JavaScript ‘include’ facility, I’ll address the provision of ‘include-once’ functionality. If you’ve not read the previous two articles, or you wish to refresh your memory, my first JavaScript ‘include’ article discussed the basic need for an ‘include’ feature, and offered a reasonable first stab at an implementation. It also outlined two key shortcomings of this first attempt. The first shortcoming, the proper handling of relative paths to included files, is dealt with in my second JavaScript ‘include’ article; the second issue of how to deal with the same files being included more than once, is presented here.

Disclaimer

Please see my JavaScript disclaimer in the first JavaScript ‘include’ article. It still applies, and constructive comments are welcome on any gaffes or oversights.

What Is Include-Once?

In addition to an include facility, many languages offer the ability to be able to ‘include-once’. Where source files are variously dependent upon other files and upon each other, it’s easy to see how the same files could be included over and over. Being able to include-once would prevent such multiple inclusions of the same file by automatically only including each file the first time it’s included.

From the caller’s point of view, using include-once is syntactically very similar to using a regular include, e.g.:

includeOnce("usefulLib.js");
usefulFn();

In this example, the ‘usefulLib.js’ file (which presumably includes the implementation of the ‘usefulFn()’ function) would only be included if it hadn’t previously been included before (irrespective of whether the previous inclusion was performed using ‘include()’ or ‘includeOnce()’).

Even with ‘includeOnce()’ available, it would still be possible to force an include to take place. In the following code snippet, both ‘someCode1.js’ and ‘someCode2.js’ would be included twice:

include("someCode1.js");
include("someCode1.js");

includeOnce("someCode2.js");
include("someCode2.js"); // Only 'includeOnce()' checks for previous inclusion.

Although for most purposes (or so it seems to me), ‘includeOnce()’ would be more useful than ‘include()’, a regular non-exclusive inclusion may still have its place. For example, you may want to include a chunk of JavaScript that generates dynamic page content in situ (using ‘document.write()’, say). If you want this dynamic content to appear more than once in the page, then it may be necessary to force the multiple inclusion of such code snippets. Ideally, then, both ‘include()’ and ‘includeOnce()’ would be available.

Implementing Include-Once

In order for the ‘include’ facility to be able to establish whether a file has previously been included, we need some means to uniquely identify files. Clearly, filename alone isn’t sufficient because different files could have the same filenames (as long as they’re within different directories). Although it might be tricky to think of a circumstance where a developer would have such an arrangement, it is possible in principle, therefore we need to make sure our ‘include-once’ feature won’t be wrong-footed by it.

Perhaps what we need is to use full pathnames (or even full URLs) to identify files. In [part 2 of this article series], better handling of file pathnames was introduced, but relative paths alone won’t cut it. If, for example, two files in different directories both include the same third file, they could refer to it using relative paths that won’t necessarily match exactly. In other words, although we’d have the same file being included twice, a casual glance at the relative paths alone might lead us to believe that two different files are being included.

Whenever an ‘include()’ or an ‘includeOnce()’ is requested, then, we’ll need to do a fair bit of processing on the supplied pathname to establish the full URL of the included file.

There are two parts to this process. Firstly, we need to take a look at the include file path we’ve been given and prefix it with whatever is required to make it into a full, absolute URL. At one extreme, this could involve no modification (in the case where we were supplied with a full URL anyway); at the other, we could be adding everything but the filename. Secondly, we need to make sure that the full URL we have doesn’t contain any ‘.’ or ‘..’ (i.e., ‘this directory’ or ‘parent directory’) parts, because this too could make two references to the same file look different from each other.

Although the process of converting (what could be) a relative include path into a full, absolute URL isn’t the proverbial rocket science, it is still a bit fiddly, and, requires more lines of code than it feels it deserves. I’ve implemented the process via two functions: ‘getRealUrl()’ that takes a full URL (i.e., one that begins with ‘http://’ and includes a domain) and parses out the ‘.’ and ‘..’; and ‘getAlreadyIncludedKey()’ that makes sure the include path is a full URL before calling upon ‘getRealUrl()’ to make sure there are no ‘.’ and ‘..’ parts.

So, ‘getAlreadyIncludedKey()’ provides us with a unique reference to a file to be included, thus giving us a means to recognise whether we’ve been asked to include a supplied file before. As the function’s name suggests, we can then use this reference as a key into a JavaScript object, for which I’ll use a global variable called ‘_alreadyIncluded’.

Using a file’s full URL as a key, we can then make a note of every file that’s included (using either ‘include()’ or ‘includeOnce()’) and automatically refrain from including it as necessary if it has been included before (using ‘includeOnce()’).

The Final Include Code in Full

It’s taken quite an effort to produce as comprehensive an ‘include’ facility as a modern language ought to offer, but here’s the full implementation in all its glory (I toyed with the idea of only including in full those extra bits required for ‘include-once’ support, but thought it would be more convenient to work with if anyone was actually tempted to try using this new facility):

var _includePath = "";
var _alreadyIncluded = {};

// Essentially 'new XMLHttpRequest()' but safer.
function newXmlHttpRequestObject()
{
    try
    {
        if (window.XMLHttpRequest)
        {
            return new XMLHttpRequest();
        }
        // Ancient version of IE (5 or 6)?
        else if (window.ActiveXObject)
        {
            return new ActiveXObject("Microsoft.XMLHTTP");
        }

        throw new Error("XMLHttpRequest or equivalent not available");
    }
    catch (e)
    {
        throw e;
    }
}

// Synchronous file read. Should be avoided for remote URLs.
function getUrlContentsSynch(url)
{
    try
    {
        var xmlHttpReq = newXmlHttpRequestObject();
        xmlHttpReq.open("GET", url, false); // 'false': synchronous.
        xmlHttpReq.send(null);

        if (xmlHttpReq.status == 200)
        {
            return xmlHttpReq.responseText;
        }

        throw new Error("Failed to get URL contents");
    }
    catch (e)
    {
        throw e;
    }
}

function include(filePath)
{
    includeMain(filePath, false);
}

function includeOnce(filePath)
{
    includeMain(filePath, true);
}

function includeMain(filePath, once)
{
    // Keep a safe copy of the current include path.
    var includePathPrevious = _includePath;

    if (isAbsolutePath(filePath) == true)
    {
        var actualPath = filePath;
        // Absolute paths replace.
        _includePath = getAllButFilename(filePath);
    }
    else
    {
        var actualPath = _includePath + filePath;
        // Relative paths combine.
        _includePath += getAllButFilename(filePath);
    }

    var alreadyIncludedKey = getAlreadyIncludedKey(actualPath);

    if (once == false || _alreadyIncluded.alreadyIncludedKey == undefined)
    {
        var headElement = document.getElementsByTagName("head")[0];
        var newScriptElement = document.createElement("script");

        newScriptElement.type = "text/javascript";
        newScriptElement.text = getUrlContentsSynch(actualPath);
        headElement.appendChild(newScriptElement);
        _alreadyIncluded.alreadyIncludedKey = true;
    }

    // Restore the include path safe copy.
    _includePath = includePathPrevious;
}

function isAbsolutePath(filePath)
{
    if (filePath.substr(0, 1) == "/" || filePath.substr(0, 7) == "http://")
    {
        return true;
    }

    return false;
}

// Strips the filename from a path, yielding everything else.
function getAllButFilename(filePath)
{
    return filePath.substr(0, filePath.lastIndexOf("/") + 1);
}

// Yields a full, real URL to be used as a file's include key.
function getAlreadyIncludedKey(filePath)
{
    if (filePath.substr(0, 7) == "http://") // Full URL?
    {
        return getRealUrl(filePath);
    }

    if (filePath.substr(0, 1) == "/") // Absolute path?
    {
        return getRealUrl("http://" + document.domain + filePath);
    }

    // Otherwise, assume relative path.
    return getRealUrl("http://" + document.domain +
        getAllButFilename(document.location.pathname) + filePath);
}

// Takes a file path as a 'full' URL (including 'http://' and domain) and
// yields a 'real' version of it with no '.' and '..' parts.
function getRealUrl(fullUrl)
{
    var protocolAndDomain = fullUrl.substr(0, fullUrl.indexOf("/", 7));
    var urlPath = fullUrl.substr(protocolAndDomain.length + 1);
    var urlPathParts = urlPath.split("/");
    var realPath = "";
    var parentCount = 0;

    for (var i = urlPathParts.length - 2; i >= 0; i--)
    {
        if (urlPathParts[i] == ".")
        {
            continue;
        }

        if (urlPathParts[i] == "..")
        {
            parentCount++;
            continue;
        }

        if (parentCount > 0)
        {
            parentCount--;
            continue;
        }

        realPath = urlPathParts[i] + "/" + realPath;
    }

    return protocolAndDomain + "/" + realPath +
        urlPathParts[urlPathParts.length - 1];
}

Conclusion

My own feeling about the final implementation is that it seems like an awful lot of code for adding a ‘mere’ include feature to a language, even if it is one that seems to be fairly comprehensive. I could have made the code shorter, of course, but only at the expense of making it either flakier or less flexible and powerful (unless we’re talking about just removing all unnecessary whitespace). If you’re prepared to put up with the limitations of the code presented in the first article, for example, then clearly it could be shorter, but only the fuller version presented here offers anything like the equivalent feature available in other languages.

Only time will tell whether I make use of my own new facility (and, in any event, it will need further testing and/or use before I’ll be satisfied that it is fully reliable with no lingering bugs), but at the very least, I’ve found that the journey has been interesting, and there are a few useful little functions and code snippets that, quite apart from forming part of the final ‘include’ implementation, may be useful in their own right. I can imagine, for example, that the algorithm used by the ‘getRealUrl()’ function for parsing the ‘.’ and ‘..’ bits from pathnames may in itself turn out to be useful one of these days.

Anyway, as ever, I’m open to your constructive comments and thoughts. And thanks for reading.

js_include_colour

JavaScript Include, Part 2

In this second article about developing a JavaScript ‘include’ facility, I’ll deal with the handling of inclusion paths so that included source files can include other source code using paths that are relative to themselves, rather than relative to the page containing the ‘<script>’ element that made the ‘include()’ code available initially. (If you’ve not seen the previous article or you need a reminder, please take a look at my first JavaScript ‘include’ article.)

Update: JavaScript Include, Part 3 article has now been published. Continue reading