Saturday, April 25, 2009

Testable code is cleaner code

I have just spent about 9 hours of my weekend spread across two sessions providing after-the-fact unit tests for about 30 methods of varying sizes (10-20 lines) written by a very much junior colleague, with the goal of getting complete line coverage, save on an irreducible minimum of calls to the outside world (in the form of external libraries being consumed by the project in question, in the main).

The main reason why the code wasn't being unit tested at the start of the exercise was that the methods were usually structured as, in the most abstract form

which meant that tests were pretty much snookered from the outset, with the code as it stood.

So, refactor

Which has removed a level of nesting conditionals around the main business, and created private methods that maintain the object's abstraction -- nothing has been made spuriously directly visible to the outside as internal or protected. If these methods were public, they would be directly testable; as it is, within the test environment they can be tested by reflection, by just feeding in the appropriate result.

And the code is cleaner already -- the specific concern of each method is now clear, and the important part of business, as extracted into ReactToSuccessInTheOutsideWorld can be tested and refactored to tighten up the first-draft flabbiness. This will usually be along the lines I outlined a couple of years ago. The retrospective tests indicate the corners that cannot easily be reached, or require a lot of duplicate set-up, and point to refactorings that keep all previous tests passing, while yielding better coverage with fewer further tests -- which should mean more cleaner code.

One of the things along this line that was brought to light by this stage of the exercise was a C# peculiarity which is at least explainable in hindsight:

where that WTF is indeed considered reachable code by the compiler, even if unreachable in practice and a blot on the test coverage -- whether because the equality and comparisons are overridable operations which could in general be wrongly implemented, or because mutable member references could potentially be changed between comparisons by a concurrent thread, it does not matter. Where we are sure that the instance is thread local, and the comparisons are sane, we can lose code


Of course within the time so far expended, the refactoring hasn't gone quite as far as pulling all those bits indicated here as separate routines out from being in-line, and many of the tests are still horribly cut-and-paste. But I can now refactor both the product and the test code, knowing that if tests fail or coverage drops, I've broken something; and I can also feel that the code under test is in a slightly better state than I found it -- both somewhat more partitioned, and with a couple of "that test didn't ought be failing like that" actual bugs fixed.

Thursday, April 16, 2009

windows "internet time" "RPC server is unavailable"

Finally (after all these years) I got annoyed enough to track down why Internet Time wasn't working on all of my XP or Vista boxes.

Despite the Internet Time synch tab being there out of the box on the system clock, there is a manual step needed to enable it. The Windows Time service needed to back it up isn't registered by default (check the Administrative Tools service applet). So, at a DOS prompt, enter

w32tm /register

Then in the Administrative Tools service applet manually start the Windows Time service.

Then and only then will the Update Now button work.


Addendum 12-Mar-12

Searching for other mentions of the service registration, there appear to be some problem reports where the service is registered, but the time synch still fails. This is not a problem I personally have ever seen, but in those articles, the fix reported in these cases is

w32tm /unregister
w32tm /unregister
w32tm /register

where you have to ignore the errors from both the first two commands to de-register the service.

Tuesday, April 14, 2009

Anime — Aria the Natural

For me, a Man-home year has passed; for Akari-chan, a whole Aqua year, from Carnivale to another New Year. Apart from the slow wheeling of the seasons, little changes. Akari and Aika are both Singles, still, and Alice a Pair, President Maa is still a scarcely weaned kitten -- though Aika's crush on Al the Gnome makes slow headway, and Aria Company gets a new mooring post and a new gondola.

Neo-Venezia is still the best anime world to live in, with nice people leading happy and unpressured lives. Most episodes are a little parable of living life to the full (though the two episodes -- the only two-parter -- spent decommissioning an old gondola somewhat pushed the limit) Except...

In the first season, Akari wandered into time out of joint on a couple of occasions. This time, she is an far more frequent weirdness magnet -- from her encounter with Cait Sith at Carnevale, through the other odd doings of Aqua's cats in old and abandoned quarters, or riding the Galaxy Railroad; summer markets where the clock stands at just past two; fox-weddings in sun-showery spring weather to ghostly passengers making night-time journeys to a cemetery isle, and more besides, when President Aria goes wandering off into the weird, like genderbent parallel worlds.

If you liked the first season, then this will continue to charm.

Monday, April 13, 2009

Film — Let the right one in (Låt den rätte komma in)

A fairly solid vampire movie, set in ~1980s Sweden, one I'd meant to see that didn't manage to make it -- despite being advertised -- for last year's film festival. A young boy, on the cusp of being a teenager, somewhat effeminate looking, is the butt of all the class bullies. And then he meets the girl who has just moved in next door, and a romance blossoms.

It eschews garlic and crucifixes on the one hand -- and all too knowing post-modernism on the other. You know what to expect -- puncture marks in necks, infection, a spate of murders. And there is the most satisfying Chekov's gun I've seen for a long while, set up when the vampire takes her first meal; though the title itself is a misdirection.

At the end, the monsters are satisfactorily despatched, and life settles back to the rhythm that it clearly had before the film began.

Oh, yeah -- having watched entirely too many fansubs in recent years, the timer of the subs on this film is worse than even the low-tier crappy speed-subbers. The titles often appeared long enough before the spoken dialog for me to read them, anticipate the Japanese (if on the betsuni, sumimasen and arigatou sort of level, at least), and then be crashed by the Swedish. And I'm so used to things like radio or TV voices-off being subbed that the omission (except for the announcement of a weather forecast, but no the forecast itself, and a chrono-locating mention of Brezhnev) felt unnatural.

Friday, April 10, 2009

Anime — Maria-sama ga miteru 3rd and 4th Seasons

The other series from Q1 that I watched -- and, the previous season, which I missed reviewing at the time (and which I now have in the form of one of the elegant Nozomi season boxes).

What to say about a series for girls, that appeals to me, at least, because it is about a strange fantastickal world, almost entirely without boys, none of whom play any significant part?

After the heavy drama at the end of the second season, the third is fairly laid-back, though not to say entirely free of social conflicts, covering a span centred on summer holidays and a school trip to Italy. And after the very demure two seasons, there is a surprising amount of fanservice (top left), above and beyond the occasional ankle or shoulder.

Fourth season opens with a new and slightly weird OP sequence (below), and an annoying sponsor (top right) -- even McDonalds is less heavy handed! We are now a year on from the first season, and Yumi is now going though what her onee-sama Sachiko did then, the troubling search for a new petite soeur to become Rosa Chinensis en bouton (bottom left).

Oh, and fanservice : Zettai ryouiki in my Marimite? It's more likely than you think! Plus easily misconstrued dialog (bottom right).

Anime — Rideback

A tale of a girl and her quasi-humanoid motorbike -- Japan really loves the transforming mechs!

It starts off as a ballet story, turns into a sports anime, with motorbike racing, but alas, soon has to turn into something vaguely political -- something which the introduction made inevitable. Ogata Rin is a ballet dancer, as her mother was, until she tears a tendon. At college, she happens into the Rideback club, and is persuaded by its president to take a spin on one of these humanoid motorbikes, which become an almost normal motorbike by folding in their arms, and doing the splits -- and of course discovers that her ballet skills allow her to easily master the most temperamental and dynamically unstable of them all.

Serious national racing ensues -- until a friend gets caught up in a terrorist hostage situation, and the mysterious Rideback girl has to come to the rescue. Implausible geo-politics ensue (though with some nice easter-eggs for the tech savvy), and, being a 12-episode series, the Big Bad turns out to be a paper tiger.

From the cues -- sakura blossoms, to cicadas, to bare trees, to snow, then back to sakura -- the story spans a year; the way it is told, with event following close on event, feels more like a few weeks, which doesn't give that impression of leisurely pace.

Overall, from a fairly thin season, not bad.

GTK-server and Erlang

I just stumbled across GTK-server in the last couple of days (occasionally /prog/ is of some use), and it struck me (as it has others) that this would make a good companion to Erlang for GUI applications. Of course, this was just before discovering that the new Erlang 5.7/R13 beta release has an experimental wxWidgets binding included; but for the moment, not only is the GTK binding rather more mature, it also has a more immediately obvious architecture for use in an Erlang application. The process separation also avoids any shared-memory issues that having a direct FFI style binding with opaque pointers could be prone to.

The general structure of a full program would be

  • spawn a process that launches the GTK-server executable
  • in a short while, construct the UI widgets
  • run the main loop as a tail-recursive call that handles events. If there are long-running activities, they should be separate processes with the usual message passing.

The following sample isn't quite like that because there is nothing calling back to it. The full implementation it would need to have non-blocking TCP, interleaved with whatever incoming messages needed to forward to the UI process. It would also benefit from some better data structure than the flat argument list here to loop/4...

A finished application would also need some real error handling, but that's possibly overkill for a proof-of-concept.

You can use fifos instead quite happily. On Windows, it looks like this:

with the rest of the changes being systematic.

Thursday, April 09, 2009

Functional thinking, unit testing, and the hole in the middle

Generalizing the "hole in the middle" pattern can be a good way to make a method that at first blush appears to be unsuited to unit testing into a fully testable one.

Consider the code

which is intended to find the app.config file for a service, and extract the WCF endpoint listening port from it. Now, even given a fully mocked ServiceInstallPath() -- assume that involves a protected abstract method somewhere in its body so we can PartialMock that -- there is a problem with that direct access to the filing system in the middle.

Well, this is something where we essentially turn the "hole-in-the-middle" around. Adjust the sequence to create the XmlDocument before looking at the file, and do an Extract Method to get

And now we replace the explicit GetFileStream with a Func<string, Stream> or an equivalent delegate type passed in as an argument

to give us a couple of new one-liner methods which can safely be tested by inspection, and the previously untestable core functionality in the newly refactored and, most importantly, functional method is now fully testable.

Yes, the code here is raw but now we have separated out all the real work, so that can be tested to destruction (and extended to handle all the XmlException and IOException cases which the original method just falls over with). The unit test fixture can provide its own Func<string, Stream> implementations that can both assert that the path is correctly constructed and can provide an arbitrary mocked stream to drive the XML parsing through various states, without having to worry about what is happening -- or not -- to the filing system.

Links for 9-Apr

A bit of a catch-up...

WPF UIs from PoSh.

F# basics -- types.

Principles of software development -- a good checklist.

Microsoft StyleCop for C# 4.3.1.3 now has a Resharper 4.1+ plugin to remove the pain of adopting MSFT's C# coding style.

The Office WPF ribbon -- royalty free license from MSFT.

The WMI team blog.

The magic behind parser combinators.

Java, JRuby and dynamic languages on the Google App Engine.

Monday, April 06, 2009

Spring has sprung

Saturday afternoon, shirtsleeves and sandals weather for cycling to Waitrose amongst drifts of sakura petals from trees near the road-side.

Sunday, plenty of gardening, digging the bit of the side bed which had lain fallow since exterminating the Japanese anemone, and starting to drag things out of the shed and garage into the new greenhouse (now with the panel that exploded in the first warm sun replaced). Plum blossom just starting to burst its buds.

Today, cycling to work, and again, sakura petals at the school. Feeling creaky from the digging yesterday, and a head wind on the way home so I pushed a couple of bits. Plum blossom now properly opening.