Friday, May 18, 2007

Links for 18-May

A bit of a catch-up:

CardSpace and decrypting Tokens

An Approach to Composing Domain-Specific Languages in Ruby

Giles Bowkett: The Business Case For Firefox

Bitwise Magazine:: What’s Wrong With Ruby?

New mailing list: HTML 5 Help

swfIR: swf Image Replacement

Five Principles to Design By

Debugging a Service on Windows Vista

The One Important Factor of programming languages

Lazylist implementation for Ruby

What Colour do you like your Objects? Pink or Blue?

Actions, Not Words

Are Web Interfaces "Good Enough"?

Your Code: OOP or POO? 

Creating User Friendly 404 Pages

Graphic designers misunderstanding Web standards

XSS bestiary

Remove empty lines from a file using Powershell.

Why <video>?

W3C's new HTML blog

Web Typography Sucks -- presentation and links to web typography resources.

Alpha release of Adobe's Apollo cross-platform runtime.

Keep your cookies straight when using ADFS

Is Your Software Team Sticky? -- do they share a coherent vision?

Primary Keys: IDs versus GUIDs

IE 7 does not resize text sized in pixels -- or any other absolute size *sigh* : Squelching what might become an urban myth

The hidden delights of Unit testing

One of the things that has left this blog light of content of late is having been provided with internal blogging, wherein I try to enlighten my colleagues. Often the entries on that blog are collations of links to and through other blogs I read. Some are from experience. Like this one.

One part of the current development project has brought home to me quite how much how serious unit testing results in cleaner code -- and that the closer you strive for 100% coverage in the testing, the more incentive there is to write that clean code.

The closer to 100% you strive to get, especially with a coverage tool (such as gcov) that does branch coverage rather than just line coverage, the more it squeezes your code. At the most brutal, the more code you have, that means the more tests there are to write to cover it all -- the incentive is there to make the code tighter, just to reduce the amount of work to do for completion.

Much of the 'C' code being written contains routines that are explicitly each a little state machine. As such the structure of a routine is along the lines of

  • check preconditions
  • determine "state"
  • "switch" on the current state
  • tidy
  • return outcome

Some of the precondition checks are assert() but others cannot be (so will include an exit-on-failure); and the switch may not be a simple flat one -- some cases may have sub-cases; and some might overlap, in a structure like

where a and b are independent.

However, even if you're not explicitly thinking of the code as a state machine as such, the routine structure is still quite generic.

Coverage testing

A set of unit tests can make sure that expected inputs map to expected outputs, both positive and negative; coverage helps tell you if you have "enough" tests. It answers the questions "Has all that code been exercised, yet?" (if not the related "if it doesn't get used, why did you write it in the first place?").

The first thing that a set of obvious positive tests will show are the bits that are difficult to reach. The obvious one is handling exception states -- and here automation and good mocks in the test framework, or your own wrapper to it, are essential. After all, exceptions are meant to be, well, exceptional, but here need to be generated on demand.

With those out of the way, the real difficult-to-reach corner-cases of the logic stand out -- and with only those to concentrate on, you're either faced with writing a lot of tests to reach them; or figuring a way to simplify the code so you don't have to.

It is often tempting to write code like this:

but, damn it, if arranging the case a and c is hard work, you don't want to go through the slog with b as well. Factoring out the special case goes from being something you could do, if you had the enthusiasm, to something you want to do, because it's less work than writing the extra tests. "Don't Repeat Yourself" becomes positively encouraged.

Coverage types

The code metric you use is important in how much benefit you can derive. For a first pass, NCover isn't too bad. But it only counts line visits, being as it is an instance of the profiling API for .Net. In particular if you have code like--

NCover will never show you that you're missing the case of zero and negative values of a. One of the up-sides of working in 'C' on a *nix platform is that that has meant that gcov is available. And that will take code like--

and distinguish between whether a or b triggered the do something -- 100% in NCover usually isn't more than 90-odd% in gcov

Squeezing out the logic

Here's a real example of code improvement in making the last step to 100% branch coverage

I had 100% in NCover; but gcov reminds me that I don't cover all the bases -- because have_token and need_token aren't independent variables : if you don't need the token, you should never have one. So, what to do when aiming for the 100% mark?

The routine here started in a state where I just enumerated all possible cases (there are more than just these), handling them individually in some sort of logical order. Now, the unit tests I already have provide me a framework to check that the code is still doing what I mean it to do when I refactor; so I can look at the code and see that what I have is actually of the form


or, more simply

refactor, re-run the tests and see that the simpler code is still right.

Similarly code guarded by an if clause, where the else is never executed under any input you can generate, perhaps because the assert() defined contract of the method or its callers enforces the constraint, can be simplified to and assert() of the condition and an unconditional block. And you get that better code because you've made yourself go the last little bit.

In the case above, user input could have, but not need, the cookie; we can't assert -- but we don't need to write (though we can) another test case to prove that is harmless, because that is just another flavour of the "else".

Thursday, May 17, 2007

Decisions, decisions

When I'm doing stuff for my own interest and enjoyment, it's almost certainly client-side applications. And unless it's something that is very definitely targeted at a particular set of OS specific functionality, I like it to be cross-platform and easy for a naive end-user to run. This was a particular pull of Java — though it was soon shown to be very definitely “debug everywhere” when the two main browser JVMs (Microsoft and Netscape) interpreted the thumb-width of a scrollbar differently (inclusive or exclusive of the range — or “lol, box-model”). And the API, even for AWT, was far nicer than any of raw Win32/Win16, MFC or OWL, back in the day.

So then the progression went AWT to GWT (a light-weight widget set that had all the missing widgets from AWT) to Swing… and there it stayed. But that did mean programming in Java, which, over the years, I've come to find lives at the wrong level of abstraction : it doesn't afford the ruthless power that C++ does (templates, multiple inheritance), but without giving very much in return (generics are latecomers, and comparatively weaksauce; there's nothing like mix-ins; and everywhere a lot of the same scaffolding that C++ would require).

Growing dissatisfaction pushed me to look at native (as opposed to bytecode) toolkits, where I could get to use C++, eventually settling on FOX, over wxWidgets. The downside of FOX is that it was not built for localisation (too many strings baked in), and the event handling model seemed to fight the language compared with Java's X-style callback registration (wxWidgets lost on having what felt like a more opaque layout model). But than meant compiling on Windows and Linux, and having to tweak platform dependent system header files (and hoping that other *nix-like platforms would work).

The moving target that is C# provided a bit of a distraction — I'll learn it for work, but are all new languages going to be just warmed-over Java? It didn't matter that Mono was providing portable CLR GUI by stages, when the language (C#) had little appeal in and of itself. So it wasn't until stumbling into Ruby and Python in the last few months that I discovered some more shiny in terms of language.

But what to do for client-side applications? Python with wxWidgets? Ruby with FOX? and what about naive users? Jython 2.2 in stand-alone mode? Pity about JRuby's sprawling nature. But what about AllInOneRuby and its friends? I had just about come down on standalone Jython, when the whole silverlight business blew up.

So now I think I know my GUI toolkit. And while we only have IronPython out (and ported to Mono) at the moment, that both Python and Ruby should soon co-exist in the DLR means that it should be possible to do what works best for the application at hand. When an object is an object is an object, much fun should be available.

IronPython and PyFit

Problem — PyFit uses the parser module.

Workround —

  • remove redundant import compiler from fit\TypeAdapter.py
  • remove import compiler from fit\taBase.py
  • remove seq_types, map_types, oper_types from fit\taBase.py
  • remove _safeAssemble from fit\taBase.py
  • remove _safeEval from fit\taBase.py and lose the ability to input non-scalar types (string being scalar); or replace its body with return eval(s) and lose the protection against wild input (sorta-OK if your FitNesse wiki is on an internal network).

Either approach breaks various of the PyFit unit tests, but does permit you to run IronPython 1.x directly, so long as you keep your cell types under control.

Special case - IronPython 2.0alpha1

This currently has problems with the type() function used in CellHandlers.isValid(). Unroll the in test as follows


which passes the unit tests.

I believe that the type() problem is known in IronPython 2.0α1, but for the record, a minimal test case, in case it persists into beta


yields

C:\Documents and Settings\Steve\My Documents\code\python>\IronPython-2.0A1\ipy.exe ipy2.py
Traceback (most recent call last):
  File ipy2.py, line 5, in Initialize
  File , line 0, in _stub_##14
  File ipy2.py, line 3, in inspect
  File , line 0, in ContainsValueWrapper##18
  File , line 0, in _stub_##19
SystemError: Object reference not set to an instance of an object.

More IronPython

Since my earlier post on the topic, I find that I've been picked up by the nifty aggregator site IronPython URL's.

At that point, I'd just started using the implementation as part of the build process for the project I'm working on at the moment — while the bulk of the choreography is handled by running devenv against the main solution, the interstitial work is done through the pre- and post-build events. In most cases, .BAT-file behaviour is enough to just invoke an executable or two with a simple command line, but anything with string handling or iteration now gets pushed into IronPython.

Why IronPython in the build? Well, given that we're building with DevStudio 2005, .Net 2.0 is already installed, so IronPython's xcopy-style install means that we can put into a project's tools folder without having to perform any change-of-enviroment on the build machines (a big no-no).

What sort of tasks are we doing?

Quite a variety —

  • Doing everything that needs version stamping from creating AssemblyInfo.cs files from templates, through web.config references to the generated assemblies to the installers and merge modules.
  • Doing pretty much everything in managing installer creation from driving Wix to create the initial single language installers, version stamping them, and then extracting the language transforms and embedding them into the master installer

From that base, I've now moved into using IronPython as a tool for helping our system test team put scripts together. Unfortunately even 2.0Alpha1 doesn't have an implementation of parser, so it can't be directly used with FitNesse and PyFit; but even so, it still makes a great utility for CPython scripts to invoke to get at awkward or tedious bits of the Win32 APIs like

  • ACLs on files and registry keys
  • the current thread identity
  • Assembly full-names

or even less esoteric things like DLL versions (even though pulling those out of PE format directly isn't that difficult) -- and without needing to check that all the necessary CPython Win32 add-on libraries are present.

It has also proved useful for quickly putting together scripts to drive web applications, by giving simple script-level access to all the System.Net and System.Xml facilities.

 

tl;dr — IronPython for the win for its xcopy-style install and out-of-the-box access to Windows APIs.

Film — El Topo

Having heard about it first many years ago in the pages of A&E, I finally got a chance to see Jodorowsky's enigmatic film of the Weird West.

Starting off as what seems to be an ultra-violent Clint Eastwood style spaghetti western, it turns into Zen quest, a tale of redemption, and then starts the cycle off all over again.

My main thoughts were to wryly observe where sensibilities have shifted in the last 35 years; and that I'm not sure what the two women with male voices were meant to represent.

Sunday, April 29, 2007

Film — Curse of the Golden Flower

Third of the sequence of visually stunning tragedies that started with Hero and continued with House of Flying Daggers.

Plot and counterplot amongst the Imperial Family wind up to a climax on the night of the Chrysanthemum Festival — the eponymous golden flower — to yield something like a Jacobean revenge tragedy with added ninja.

All style, very little substance — but what style it is.

[Now playing - Planet Rock]

Nature notes

Sitting out in the garden blogging, after having done another batch of garden work, and tidying up the garage. Still a lot of stuff for the tip, and more for jumble. Cherry blossom is falling in the breeze, carpeting the lawn like snow.

There's a lot of tidying to do after last year's total neglect, but when there are wanted plants in amongst the weeds, simple clear to the surface and suppress won't do, so it goes more slowly. And unexpected tasks like removing the suddenly expired clematis add to the work. At least there's a natural limit — stop when the green bin is full.

The frogs are appearing in the pond again, lurking at the surface; and there's at least one newt as well.

[Now playing - Planet Rock]

Sunday, April 15, 2007

Anime — Hataraki Man

A rare thing, a josei anime, i.e. aimed at the 20-something woman.

Hiro is an editor at a weekly magazine that does news, comment, investigative journalism, and serial novels; possibly a little bit too masculine in her drive for her job for her colleagues : she gets called a “Hataraki man” — a working man — and her managing editor, on hearing she has date, wonders if it's with another woman.

But with all this work, she also has a problem with her lifestyle. She and her boyfriend never seem to have gaps in their schedules at the same time.

I just wonder if Shinji is a name like Kevin, with associations of being feeble; whether Ikari-kun has had a pervasive influence; or if this wimpish Shinji is just a coincidence.

In the usual way, to be thought half as good as a man, she had to do twice as well. And again, for her, this is not difficult…

This, in 11 episodes, is a slice of her life, its ups, downs, praise from and friction with, her colleagues.

Surprisingly compulsive viewing, for all that it is entirely mundane. — the Man Switch gag being a one-off.

And then there was one…

Friday night, Penny was walking a bit stiffly — she didn't seem to find any of my prodding her painful, so I didn't think it could have been serious damage. Perhaps another case of a bit of a muscle strain from getting a claw caught in the throws over the furniture. That had happened in the autumn, when I'd come hom to find her hanging like a bat from the side of one chair, and going into all sorts of muscle spasm when unhooked.

Saturday morning, I came downstairs soon after seven to see her floundering about on the kitchen floor, trying to escape from the fetters that were making her hindquarters useless, and front legs almost so. Unlike Lady May, who had just sat herself into a tidy little bundle and purred as she faded, after she had a stroke, Penny was clearly going to fight with all the strength left to her.

So, the unpleasant task of bundling her into a towel, into the cat-box, for the one-way journey to the vet on an emergency call-out.

And after, cycle into town for the shopping I was going to do anyway, and stop at Grantchester on the way back to get hammered.

More about Penny.

Saturday, April 07, 2007

More progress

The on-going cycle-path saga has really geared up. From last week's state, the entire run across the M11 from roundabout to roundabout has been taken up, except the unblemished surface on the bridge; and now the edging and bedding is being replaced. At the current rate, in a couple of weeks, it might at last be all done!

Anime — Simoun

Simply the best anime title of 2006 (because the closest competitors, Akagi and Mushishi are technically 2005 titles that ran through the winter half 05-06.

And a woefully under-appreciated title it was.

The original fan-sub group that picked it up usually handles shoujo-ai titles; and the “key-turn” ritual (middle left) for starting up the Simoun (the flying machines, see top left) made it look like just another excuse for very pretty backgrounds and girls getting friendly together. But it turned out more complicated than that, and was left to languish in favour of more accessible highschool-romance titles, until picked up by the most dedicated and special-purpose group of fansubbers whose product I have followed.

Simoun-Fans, an essentially ad hoc grouping, put together the most polished translations and sub-titling (including credits for the seiyuu against the characters during the OP, rather than the usual self-congratulation; that was left for a brief screen at the very start, before the TV footage). Of course, the polish came at a price — episode 26 wasn't subbed until a year after the first episode aired.

OK, the story, and why you should watch this title…

On a world that is not ours — two suns in the sky, for one thing — a transcendent civilisation rose and vanished. In its wake, the remaining people could unearth the helical motors, the snail-shell parts of both the Simoun and other powered devices (trains, boats, the old “tramp steamer” Messis top right, …). But only the Holy Land of Simulacrum has harnessed them, and the casual flight it offers. Other lands have more steam-punk technology, and seek the secret of the simoun. So war breaks out…

In that world, all children are born as girls, and in Simulacrum choose to be man or woman at coming of age in their late teens. All the parts — even the men, are voiced by women; and, of course, young men are hard to tell from young women — the adulthood change is not instantaneous, as shown in the character of Wapourif, the chief mechanic to the simoun.

While lesser flying craft can be piloted by anyone, the simoun needs to be driven by two girls; and these pilots are drawn from the ranks of the priestesses of Tempus-Spatium. While two priestesses at the helm they can produce magical effects by drawing glyphs in the air (called Ri-Maajon; middle right is the Silver Ri-Maajon), as part of religious ceremonial aerobatics. And as priestesses, they are allowed to defer a while the choice to become adult.

So, a group of priestesses become, overnight, the necessary front line of the Simulacran fighting forces. Few can handle the mismatch between their vocation and their new orders — and when the new overwhelming forces of Argentum actually bring down a choir of simoun, many depart into adulthood. Only the latecomer, Aaeru (lower left), even refers to what they do in military terms, rather than liturgical ones.

So, it's a war-story; but it's character driven drama, of love, sacrifice, choices, and growing up (or not, as the case may be).

After 25 episodes of brilliance, I was anticipating the finale with some trepidation — too many series drop the ball at the end. This, however concluded with an understated and open ending which was as satisfying as could be, knowing that this story had at last come to its ending.

Thursday, April 05, 2007

Undocumented Jython — Java callable Jython class idiom

You have to do



and not



in order to make jythonc generate the function calls you want in the intermediate Java code.

And as I'm in a “Jython calls Java calls Jython” state, doing some transcoding/refactoring, I have still not managed to get Jython at the front to call nicely into the Jython at the back.



causes

method myPackage.Backplane.performSetup of myPackage.Backplane instance 1
Traceback (innermost last):
  ...
AttributeError: abstract method "performSetup" not implemented

despite it being there quite plain as day:-



and despite Java code calling it quite happily.

*sigh*

Monday, April 02, 2007

Anime — Mahou Shoujo Lyrical Nanoha StrikerS

Suddenly -- fansubs.

OK, so the only raws to hand are poor quality, but this was out within about 24 hours of the show airing.

This episode was hyperkinetic -- and had enough Engrish in it to make it roughly comprehensible even with minimal Nihongo -- I wonder if they can all keep it up like this. I didn't think it was really possible, but the casual magic use level has escalated from A's high points -- I'm getting serious 'Doc' Smith flashbacks here.

I would hope that after this all-action grab-your-attention episode, next time gives us a bit of exposition.

Sunday, April 01, 2007

New Season

A bright sunny day -- good for pottering about in the garden and trying to beat back the worst of the weeds. Suddenly, it was hot enough to get hot and sweaty working out in the direct sun.

Meanwhile, in other news …

…first episode aired this afternoon local time, and this evening I was a sad enough bunny to hunt down the first LQ raws to watch. Beamspam being a universal language, and Raging Heart still giving occasional commentary, I could figure out most of what was going on. Probably a couple of weeks for subs, though.