Node

I’m looking for a new toy to play with. Something bold and new, some great new ‘THING’ to identify with. A change from the desktop world of Eclipse + Java. I guess it has to be web-based.

I put together this list of thrilling new (and not so new) trends:

  • Ruby on Rails
  • Node.js
  • Angular.js
  • Go
  • Rust
  • Julia
  • Meteor
  • Elixir

Sounds exciting, but what do all these languages and frameworks boil down to? JAFW Just Another Fucking Website. Phooey.

As I’ve spent so many years developing apps for the desktop and on mobile (C, Java, Swing, Eclipse, SWT, EMF, XML, iOS, Objective-C, Swift) I thought I better take a look at developing for this new-fangled “web” thingy.

At first I took a look at Ruby on Rails, and found a nice tutorial. I was initially attracted to Ruby because of its colour, and it’s a jewel and a girl’s name. I also like the writings of DHH, the creator of Rails. I like it that it’s “opinionated”, like me. That means that the framework imposes a certain way of working, things have to be in the right place. It uses “convention over configuration”, meaning that I make less decisions and everything is in its proper place. I like everything in its proper place. But I don’t want to learn Ruby. In fact, I really don’t want to make JAFW, either. So I thought about it and dumped it. At least the tutorial taught me how to deploy to Heroku.

So Node.js.

It means using…JavaScript. Phooey and big :stench:

An untyped language.

CoffeeScript on top of it? Nope, too far away from the metal. A meta-language on top of a scripting language? Double :stench: Looks like I’ll have to bite the bullet and hold my nose…JavaScript it is. JavaScript is useful, right?

So far the story consists of Node, NPM, WebStorm and a JS book…

…I’ll be back. Meanwhile, here’s that prince of TrendMongers, Greggery Peccary:

Greggery_Peccary__s_Invention_by_fig13

With his eyes rolled heaven-ward, and his little shiny pig-hoofs on the desk, Greggery ponders the question of ETERNITY (and fractional divisions thereof), as mysterious angelic voice sing to him from a great distance, providing the necessary clues for the construction of this thrilling new TREND…

Software Craftsmanship

I was beginning to wonder if anyone cared about quality over price in anything any more. We see it everywhere – macdonalds, supermarkets. and in software. it seems like a race to the bottom in the X factor generation.

Another term is artisan. As used by Beedocs

I like that term but was disappointed in the reaction it got here:

Don’t be a Coder, Engineer, or Developer: be a Software Artisan!

As the guitarist Robert Fripp says in one of the Guitar Craft aphorisms, “how we hold the pick is how we organise our lives”.

And then I discovered Software Craftsmanship by Sandro Mancuso.

Software Craftsmanship

…we can say that Software Craftsmanship is a better metaphor for software development than software engineering. Software Craftsmanship sees software as a craft and compares software developers to medieval blacksmiths.

Mancuso’s personal definition of “Software Craftsmanship”:

Software craftsmanship is a long journey to mastery. It’s a mindset where software developers choose to be responsible for their own careers, constantly learning new tools and techniques, and constantly bettering themselves. Software Craftsmanship is all about putting responsibility, professionalism, pragmatism, and pride back into software development.

And, for me, the key phrase:

[to] delight customers helping them achieve whatever they want to achieve

These are important qualities to have in our lives and in our code. To paraphrase Fripp – “how we write our code is how we organise our lives”.

Developers are taking the matter into their own hands and are trying to change how the industry sees software development. They are doing that not just by proposing new and revolutionary processes but also by showing their customers that they care about what they do. Developers are showing their customers they want to work together with them in order to produce great and long-lived software, helping them to achieve whatever they want to achieve.

(Emphasis mine)

Perhaps if more software “engineers” played a musical instrument, painted, or were artists they might like the term “artisan” or “craftsman”.

And I particularly loathe the term “Software Engineer”. I am not an engineer. Isambard Kingdom Brunel was an engineer. I would rather be called a “hacker” than an “engineer”. (Actually, my chosen term is “code punk”).

Asynchronous Unit Testing in Xcode 6

Last year I described a method to implement asynchronous unit testing in Xcode 5.

Let’s remind ourselves of the problem with asynchronous unit testing. Many APIs on the iOS platform themselves are asynchronous. They have use callback invocations to signal when they’re completed, and these may run in different queues. They may make network requests or write to the local file system. These can be time-consuming tasks that need to run in the background. This creates a problem because tests themselves run synchronously. So our tests need to wait until they are notified of when the running task has completed.

I proposed a method that entailed setting a boolean flag in the unit test and looping in a while() loop until the flag was set to false, allowing the test to complete properly. This method worked most of the time but I have never been happy with it, regarding it as a bit of a kludge. In that blog post I concluded:

I still have my reservations about this technique, and I’m still looking for the perfect solution for asynchronous unit testing in Xcode. You would think that Apple might have provided a solution in XCTest, perhaps similar to the implementation in GHUnit.

Here’s what the Objective-C version of a bare bones example asynchronous unit test in Xcode 5 using the old method looks like:

- (void)testSaveAndCreateDocument {
    NSURL *url = ...; // URL to file
    UIManagedDocument *document = [[UIManagedDocument alloc] initWithFileURL:url];
 
    // Set the flag to YES
    __block BOOL waitingForBlock = YES;
 
    // Call the asynchronous method with completion block
    [document saveToURL:document.fileURL
        forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success) {
            // Set the flag to NO to break the loop
            waitingForBlock = NO;
            // Assert the truth
            STAssertTrue(success, @"Should have been success!");
        }];
 
    // Run the loop
    while(waitingForBlock) {
        [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
                                 beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];
    }
}

In fact, because I was re-using the same pattern in many of my tests, I converted parts of it to a Macro that had to be included in each header file. Also, I noted that under some conditions the test didn’t complete properly.

Well, the good news is that, less than a year later, Apple have delivered a means to implement asynchronous unit tests in an intelligent and offcially supported way. Furthermore, not only have they given us a new version of Xcode 6 (still in beta at the time of writing) with this new unit testing framework, but they have also delivered a brand new programming language, Swift. I’ve spent some time over the last few weeks converting a hefty chunk of Objective-C code to Swift, and in converting my Unit Tests to the XCTest framework I implemented Apple’s new methods for asynchronous unit testing. From now on, all of my iOS coding is going to be done in Swift, so the examples below will be in Swift, too.

So, how does it work? In Xcode 6 Apple have added some extensions to the XCTestCase class, and I’m going to focus on two of them:

// expectationWithDescription
func expectationWithDescription(description: String!) -> XCTestExpectation!

// waitForExpectationsWithTimeout
func waitForExpectationsWithTimeout(timeout: NSTimeInterval, handler handlerOrNil: XCWaitCompletionHandler!)

There’s also a new class, XCTestExpectation which has one method:


class XCTestExpectation : NSObject {
    func fulfill()
}

Basically, you declare an “expectation” in your unit test, and loop in a wait loop waiting for the expectation to be fulfilled in your code. It’s the same pattern as before, but with more options. Here’s the old Objective-C code converted to Swift using the new framework:

    func testSaveAndCreateDocument() {
        let url = NSURL.URLWithString("path-to-file")
        let document = UIManagedDocument(fileURL: url)

        // Declare our expectation
        let readyExpectation = expectationWithDescription("ready")

        // Call the asynchronous method with completion handler
        document.saveToURL(url, forSaveOperation: UIDocumentSaveOperation.ForCreating, completionHandler: { success in
            // Perform our tests...
            XCTAssertTrue(success, "saveToURL failed")

            // And fulfill the expectation...
            readyExpectation.fulfill()
        })
        
        // Loop until the expectation is fulfilled
        waitForExpectationsWithTimeout(5, { error in
            XCTAssertNil(error, "Error")
        })
    }

In line 6 we instantiate a new instance of XCTestExpectation, named readyExpectation. We give it a simple description for convenience, “ready”. This will be displayed in the test log to help diagnose failures. It is also possible to set more than one expectation as a condition. Then in line 9 we make the call to the code that needs to be tested. In the completion handler, after making our tests, we call the method fulfill() on the expectation. This is equivalent to setting the flag to false in our earlier Objective-C implementation.

The last block of clode starting at line 18 runs the run loop while handling events until all expectations are fulfilled or the timeout is reached. I set the timeout to 5 seconds to be on the safe side.

And that’s about it. There’s more you can do with the new additions to the unit test framework, such as key-value observing, and performance metrics, but the above should be sufficient to get going. Finally, we have a proper framework for Asynchronous Unit Testing in Xcode!

Eclipse and Asynchronous Unit Testing

I’ve been retro-fitting hundreds of JUnit tests to Archi‘s code base. It’s a Zen meditation, as the process of devising the unit tests ensures that I re-engage with the code, clean things up, refactor here and there, and finally understand what that nifty algorithm does that I wrote 3 years ago. Like children not eating their greens, no-one wants to write unit tests. But it’s a valuable thing to do and rewarding, especially when you see the green bar in Eclipse:

Testing

Perhaps the process of testing and being rewarded by the green bar is an example of “gamification”? Maybe, but I’m not interested in vacuous neologisms, I’d rather just get stuff done.

Some tests that I wrote were failing. The code that these tests was calling depended on events occurring in the UI of the application, such as an editor window opening. The tests were finishing before the editor window opened. Not sure what to do about this I went for a jog to have a think. And then I remembered that I already had the answer in one of my own posts, Xcode and Asynchronous Unit Testing. This has turned out to be quite a popular post in the Xcode and Objective-C community, solving a common problem. So I wondered if Eclipse would be happy with a similar pattern. I’m never sure what’s going to happen when I start playing with threads and dispatch queues.

Here’s my solution, an abstract Java class called “AsyncTestRunner”.

public abstract class AsyncTestRunner implements Runnable {

    boolean waiting = true;

    @Override
    public void run() {
        stop();
    }

    public void start() {
        Display.getCurrent().asyncExec(this);

        while(waiting) {
            if(!Display.getCurrent().readAndDispatch()) {
                Display.getCurrent().sleep();
            }
        }
    }

    public void stop() {
        waiting = false;
    }

}

This class implements Runnable which has one method, run(). This run() method will be called by the current Display instance asynchronously in this line:

Display.getCurrent().asyncExec(this);

Meanwhile the read and dispatch process will go off and do its thing in the event loop:

while(waiting) {
    if(!Display.getCurrent().readAndDispatch()) {
        Display.getCurrent().sleep();
    }
}

This ensures that UI tasks can be completed.

Here’s an example of how we use it:

AsyncTestRunner runner = new AsyncTestRunner() {
    @Override
    public void run() {
        super();

        // Run some code that needs testing in the UI
        Object someThing = ...;
        assertNotNull(someThing);
    }
};

runner.start();

Here, we create a new anonymous instance of AsyncTestRunner and implement run() with the testing code and then call its start() method. Be sure to call super() in the run method to invoke stop() which sets a boolean flag to false which breaks the event loop in the start() method.

The class may seem verbose with its stop() method, you could simply directly set the waiting flag to false, but I wrote it like this so it can be sub-classed and to make it obvious what’s going on. I also like the idea of a run() method consisting of one stop() method.

public void run() {
    stop();
}

Very Zen.

So far it works in both Eclipse 3.8.2 and Eclipse 4.4. I may find a gotcha further down the line, and I may refine the class in the future, but so far it’s looking good. If it can be improved I’d be glad to hear about it.

Do you love your users?

Alan Rusbridger, the editor of The Guardian newspaper, was recently asked by a UK home affairs committee investigating the Snowden leaks, “Do you love this country?” This is not a question I will answer, but I do find myself asking a similar question of software developers – “Do you love your users?” Or, put another way, “Why do you hate your users?”

As the developer of Archi, the free ArchiMate modelling tool, I’ve put in many hours of my time, and much soul-searching, trying to create an application that works simply and elegantly, hiding complexity from the user and, above all, not crashing. I’ve thought deeply about what users want and what they probably don’t want, and I’ve listened to, and responded to, user feedback. So my answer to the question, “Do you love your users?” is unequivocally, “Yes!”

I’d like to illustrate this with an example of the process of thinking about usability in my software, and finish with an example of “user hatred” in another piece of software.

Show me the love…

I just implemented a new feature in Archi – to let the user define the line colour of a selected object in a diagram. This wasn’t too difficult, I just followed the standard presentation in the Properties pane. But then it got a bit more complicated when I added an additional option to derive the selected object’s line colour from its fill colour. Again, this wasn’t too hard, but it did present a usability challenge – one option negates the other. If the latter option is selected in the application’s global preferences, then any user line colours are ignored. So how would this look in the object’s Properties pane?

Archi Properties pane
Why are they disabled?

The problem is that the line colour selector buttons are always disabled. Whatever you do, they remain disabled since the global preference is set to derive line colours from the object’s fill colour. So why on earth are the buttons there? Perhaps the user needs to do something special to the selected object to enable them? Search in the user manual? Perhaps phone the help-desk? As it stands, this is a perfect example of the software designer hating their users. It’s the equivalent of inviting someone to dinner and then hiding the food in the cupboard.

So let’s show some love and try and solve the problem. Let’s kindly explain to the user that if they want to set their own line colour, they should have not been so stupid to have set it in the application’s preferences in the first place:

Archi Properties pane - better
Hmm…why should I?

Well, why should the user have to do that? They can’t even remember where the preferences are, let alone which preference to look for. Out with the manual again!

Perhaps the better solution is to not only explain why the feature is disabled, but also to offer a link that will open the preferences dialog window and take the user to the preference that will solve the problem:

Archi Properties pane - much better
A bit better, but…

Clicking the link takes the user to the Preferences dialog window:

Archi Preferences dialog
Preferences dialog – set it here

This is not a perfect solution, since the user has to think about whether to disable or enable the option. However, it’s a lot better than before. But wait…

…why not just completely hide the colour buttons in the Properties pane when the feature is not available? This way you wouldn’t even need to show an explanatory text and link. Well, I thought about this and this creates a different problem – the user might never know that the line colour feature exists. By greying out the buttons I’m providing a hint to the user that the feature is available under some circumstances. The additional explanatory text and link then takes the user to the preferences dialog so that they can see for themselves how and why this is an option – coaching and coaxing the user.

Even this solution sucks. There are just too many buttons cluttering up the screen. Back to the drawing board.

This is better:

A better solution
A better solution

Here I’ve combined all buttons into one control – the colour selector, as before, and the “Default” and “Preferences” into a drop-down menu available from the right of the selector. I even re-used the control for the Font selector. Nice.

And now for something completely different…

That is a small example of the process I go through when demonstrating the love I have for Archi’s users. But what about software developers who seem to hate their users? I give you Protégé, an open source ontology editor from Stanford University. Here’s the opening screen on Windows:

Protege - WTF?
Protege – WTF?

This just broke Software Rule #1 – Don’t Throw Shit at the User.

Ok, how about simply opening a file in the current editor window? Here’s the result:

Protégé - oh dear...
Protégé – oh dear…

Protégé also has a menu item called “Refresh User Interface“. Really? You don’t get a dog and bark yourself. Come on, this is supposed to be Stanford Frickin’ University.

You know what? I think the Protégé developers hate their users.

Begin typing your search term above and press enter to search. Press ESC to cancel.