Monday, 28 March 2011

City Life

An example of London life that happened to me in the week.

I'm heading back to Liverpool Street to catch the train home -just another worker ant focused on the clock, when :

'Can I ask you a question'

Oh god I think, I take a look at the questioner, no clipboard that's a good sign, scabs on the face and swaying a bit -not so good. Still  I've got 5 minutes to spare, it might be quicker to play along with him.

'Go on then -if you're quick'

'Do you remember Dudley wossname -was in that film with that bird'



Ok, that came from nowhere, however I'm of the vintage that Bo Derek made a big impression on (well the male half anyway -and if the number of cornrow hairdos that were about on blondes at the time was any guide- the females weren't entirely immune).

'Uh, yes Dudley Moore'

'Who was it who was his partner, you know in the act, do you know?'

'Peter Cook' I reply.

'Brilliant mate -I had this bet with my mate that he was wrong and you've won me 20 quid'

'Who did he think it was then?'

'Peter O'Toole, wanker. I told him he was Dracula.'

Made me smile. And it's an excuse to put up a picture of Bo.



Wednesday, 9 March 2011

Turing got there first -again.

Alan Turing

I was doing some research into test driven development and came across Tony Hoare's paper  The Emperors Old Clothes . Hoare is a big name in the history of computer science, inventing Quicksort at an early age and then C.S.P -I have had the misfortune to program in Occam (and Ada) which implement this, nothing wrong with the concept or really the language -but Occam simulated on a vintage PC wasn't good.

Hoare's paper is well worth a read, both from a historical perspective and for the all too familiar view of projects going horribly wrong -in this case Algol 68, PL/1 and Ada. Helped by mandated use from the military Ada did finally take off -but so did the Bristol Brabazon - but the language failed to achieve the popularity hoped for and we all ended up using C++ for our sins (which must have been many).

Anyway, back to Turing, it seems he wrote a paper in 1949 (yup) entitled 'Checking a Large Routine' the opening paragraph reads :- 
"How can one check a large routine in the sense of making sure that it’s right? In order that the man who checks may not have too difficult a task, the programmer should make a number of definite assertions which can be checked individually, and from which the correctness of the whole program easily follows"
 Sounds like the basics of Test Driven Development to me.


Sunday, 6 March 2011

Why I hate setters and getters (especially in PHP).

Whatever you think about object oriented programming (and the phrase ‘Emperors New Clothes’ has been known to pass my lips, although I’m not so dogmatic now.) there’s a point where the syntactic sugar turns to syntactic saccharine -and that point is accessor methods.

Whilst I acknowledge the usefulness of encapsulation and limited visibility I loathe having to write reams of setThis() and getThat() for every blasted variable I want to use. I was going through the Zend Framework tutorial and there’s a simple four field model in there, which generates eight methods, life is too short. The model already exploits __set and __get which allow controlled access to hidden properties, so why not go the whole hog? Here’s a version that calls an accessor method if there is one (you might need to do some extra processing or formatting in it) but otherwise returns the protected variable.


class SomeClass {
    protected $_comment;
    protected $_created;
    protected $_email;
    protected $_id;

    public function __get($name)
    {
       $method = 'get' . $name;
       if (('mapper' == $name)) {
           throw new Exception('Invalid guestbook property');
       }
       if(method_exists($this, $method)) {
           return $this->$method();
       }

       $attr = "_$name";
       if(property_exists($this,$attr)) {
           return $this->$attr;
       }
       throw new Exception('Invalid guestbook property');
    }  
}

Instead of defining a setId method and calling a $someObj->setId(3), you don’t define the method and use $someObj->id = 3.

Personally I’d probably turn this into an abstract base class to support the model classes, leaving the individual classes to supply specific accessor methods if needed -thus getting rid of reams of code that I’d need to maintain. There are times when you wouldn’t use this approach, but for the database mapping example given it’s a bit of a no brainer.

Why especially in PHP? Because it’s not an O.O. language, it’s a scripting language, I like the ability to use O.O. syntax when I think it adds clarity to the program and I like the fact that I don’t have to if I think it makes life harder. Additionally libraries like Zend Framework should make life quicker and easier, it is the point of them after all, and not slower, harder and more verbose.

BTW don’t let this put you off Zend Framework, it’s a good piece of work and I’ve built a few systems using it.

Tuesday, 15 February 2011

The Blind Watchmaker

by Richard Dawkins


The book that describes the biomorphs. It is much more than that, it aims to explain how a complex world can arise from blind chance and natural selection with no need for an 'Intelligent Designer'. I think that this is an excellent book, whether or not you believe in evolution it explains concepts that are key in several areas. A prime example is complexity and how it can arise from simplicity in small steps. The relationship with probability is explored too -together with some estimates of how likely some out comes, ssuch as life in the universe, are.

Dawkins is a good writer with a clear style who uses good examples to illustrate his points. From bats, to crocodiles; from ants to eyes; he takes examples from across the natural world. Consider the eye, one of the claims of intelligent design is that something as complex as an eye couldn't have arisen from natural selection and an 'incomplete' eye is no good. This is patent rubbish, at some point in evolutionary history there were no eyes and then the ability to tell light from dark evolved -that's a useful thing to have, if you're a worm you don't really need any more than that. In addition there are eyes at different stages of completeness within nature -the nautilus has an eye like ours, but with no lens; our eye is wired up backwards - that of the octopus is wired forwards; the point is that you don't need a perfect eye, just one that is good enough and better than your competitors.

Which reminds me  of the joke about the wildlife film makers who are watching a cheetah when it spots them and puts the team at the head of the menu. As it charges towards them , the sound recordist starts swapping his boots for trainers, when the camera man points out that he still won't be able to out run a cheetah simply because he's wearing Reeboks. 'Mate' replies the recordist, 'I don't have to run fatster than the cheetah -I just have to run faster than you'.

There is lots of other good stuff in here, genetic algorithms, cooperating genes, discussions around Lamarkism and Punctured Equilibrium, genetic explosions and spirals, the tail of the peacock and convergent evolution. All in all very highly recommended.

Thursday, 10 February 2011

First Fix

A bicycle crash is only a matter of time.

First Impressions - I like it, it's like being a kid again, the pedals go round all the time, whack you on the back of the leg if you're pushing the bike and you lose them going down steep hills. The bicycle itself needed some setting up of the saddle, seat post and handle bars, but now that is done it feels pretty comfortable. Compared to my tourer the Atlantis is quite wobble and twitchy, I think that this is because the frame is a bit shorter.

The main difference to a normal bicycle is that you can't coast, even when you've just got on you have to keep the feet moving. Secondly, you can slow yourself down by resisting the pedals as they go round, sort of back-pedalling but your legs still go forwards. Then there's the gears or rather gear, being unable to change gears, or coast, means the pedals spin like the fabled dervish going downhill and that you have to get out of the saddle and stand on the pedals to go up. Once you trust the bike, up is easier than down. So long as it doesn't go on too long.

This should be good for getting the legs into shape -there a plan, okay vague idea, to do the c2c this summer, and up north they have hills! And it is fartlek training for free.

My longest run so far is only 8 miles, I'd like to get to double this at some point, but any longer than that and gears are the way to go.

Overall it's a more physical ride and also a smoother one as there's not the clunking gear change, probably especially noticeable on my tourer with its down tube shifters and mongrel  drive train. Since your legs are always turning you are always thinking about pace, whether it's recovery, a sprint downhill to get you up the other side, or resistance to stop the bike running away with you. Cycling becomes more involving, and thus more fun.

Monday, 7 February 2011

Biomorphs and Javascript - a marriage made in purgatory.

Well it definitely isn't heaven, and it's not really hell (6502 assembly programming on a machine with no permanent memory and a dodgy power supply comes close).

I'm not sure I'm ready to devote a whole post to how crap Javascript is, I imagine that there are probably whole sites, probably complete universes, devoted to just that topic. But here's a handy hint -your variable isn't locally initialised unless you stick var in front of it, but your program will run anyway, perhaps almost correctly. Having been corrupted by languages where you don't declare variables, just use them, I got some unexpected side effects with the Biomorphs and the variables became global -even though they had been declared locally, inside a function scope. Enough, I've got to go and fill in the hole in the plaster where I was banging my head on the wall.

The biomorph program has had an overhaul and now produces, occasionally, things that look like biomorphs.  The main changes have been to switch from polar to Cartesian coordinates and to introduce randomness. The coordinate switch allows the introduction of a 'gene' as a string of x and y coordinates, and having this gene means that it can be populated randomly and thus gives us the potential for 'evolution'. Here's the guts :

function bio_morph()
{
        this.gene = new Array(9);

        //Generate a random gene 7 is the number of generations and gene 8 is the stem length
        for(var i = 0; i<7; i++) {
                this.gene[i] = Math.round((Math.random() * 20) -10);
        }
        this.gene[7] = Math.random() * 10;
        this.gene[8] = Math.round(Math.random() * 10);
}
Multiplying by 20 and taking away 10 allows us to have negative numbers in our random sequence, so the creatures can gro up and down, left and right.

All that remains is to produce an array of the critters and allow you to choose the one start new generations from.

As always take a look at the main biomorph page.

Thursday, 3 February 2011

KISS My Cog. Fixie Bicycle Conversion.

Atlantis Rising

Keep It Simple Stupid, about the only useful principle I learned at university. It applies to software, life -and bicycles. Fixed gear bicycles are the new black (or rust red) although not themselves new, a pennyfarthing would have been fixed, and I remember getting smacked on the back of my legs by my pedals at a young age. Out of nostalgia, or trend following, I've been thinking about building a fixie, then a friend donated an old Dawes Atlantis with a Reynolds 501 frame and off we go.

The main selling point for fixed gear bikes is simplicity. Only one gear, so no deraillieur, shifters and associated nastiness, arguably you don't even need brakes (although this would not be legal in the U.K.) -so you get a simpler and lighter bike. Secondary points are that  it makes you a better cyclist, you don't have to think about gear changes, your pedalling style is  improved; and your legs get stronger. Since I have the family sparrow legs this can only be good.

KISS in action

Firstly some research, I can recommend the late, lamented Sheldon Brown and also Charlie the Bike Monger he's more single-speed but some good advice and a good source of parts.

The original rear wheel on the Dawes had a floppy axle and an obsolete SunTour cassette, so I decided to take the line of least resistance and buy a new wheel with a flip-flop hub from Charlie. A flip -flop hub takes a track cog on one side, which is screwed directly to the hub with a counter threaded lock ring (both supplied with the wheel), the other side takes a BMX style cog with an integral freewheel. The idea, from Sheldon, is to have an easier cog on the freewheel side and use this to get you home when the going gets a bit too tough. Since the wheel came with a 16 tooth cog I got a cheapo 18 tooth freewheel. Aside from being tight, I might need to find the right cog and chainring (that's the big cog attached to the pedals)combination  by experimentation, so chaep cogs first. You also need rim tape for the wheel, I forgot this and live nowhere near a bike shop, last pair of wheels I bought came with the tape installed -so put a note on your page Charlie, some of us are thick!

Whilst waiting for the bits to arrive I sorted out the brake cables -using a funnel of insulation tape to get oil down them, start off wrapping the tape tightly around the cable outer then looser as you get to the end.

When the wheel arrived cog installation was simple- just screw on, lock ring similar but the wrong way. Next the chain, it is important that this is taut but not tight, there's no deraillieur to take up the slack, and that the run between chainring and cog is straight. Luckily it seems to be straight on the inner ring of the Dawes, so all good. Measure up the chain for both cogs, by offering it up, and remove any surplus links, I bought a half link to get the length just right. Then get the chain taught and nip up the chain side nut first, straighten the wheel, then the other side. Make sure that the wheel nuts are bastard tight, unfortunate things can happen to ones manhood  if the chain comes off the cog.

Then it was on with new Aztec brake blocks (twice the braking area of the '50s clone on there), adjust the saddle -which was at a rather alarming angle, and off we go for a spin around the block. And spin you do, no freewheel, no coasting, your legs turn all the time, you can even slow yourself down by back pedalling. Strange but fun, as the actress said to the lady-boy bishop.

I'll let you know how I get on.

linkedin