Just A Summary

Piers Cawley Practices Punditry

It's not just modern music Giles...

Posted by Piers Cawley Sun, 04 Jan 2009 21:07:00 GMT

Giles Bowkett’s just written up an example of the way that sampling is an essential part of modern music and he’s right. But he doesn’t go far enough really. Sampling has always been an essential part of all musics. What’s the twelve bar blues form after all? Different artists put their own spin and lyrics on top of it, but it’s always the same chord structure and it’s often the same words forming the backbone. I don’t know about you, but I can’t hear the words “I woke up this morning” without expecting a blues to follow.

Meanwhile, in folksong it’s long been suggested to collectors, the people who go and record songs from “the folk” that they might try asking if their informant “knows a song about a milk white steed?” I’ve certainly lost count of the songs containing a verse in which the hero or the villain tells someone to “Saddle me my milk white steed”, or someone rides by on a milk white steed. When the heroes of folk song aren’t riding white horses, they’re leaning their backs against oaks or swearing that something will not happen until apples grow on cherry trees.

Sampling, remixing, borrowing, copying, adapting, influencing – call it what you will, it’s at the root of so much art and craft. Now, I could come over all Cory Doctorow and bang on about the vital importance of remix culture, but Cory does Cory better than I ever could, so I’ll just try and leave you with the idea that this is not new. Michelangelo and many of the great artists of the renaissance started their careers by copying works from classical antiquity after all. My favourite example has to be the story of how Mozart heard Allegri’s Miserere sung in the Sistine Chapel when he was fourteen and, that evening, wrote out the parts from memory, apparently returning again the next Friday to make minor corrections. So Mozart, considered one of the most prolifically creative musicians ever, seems to have been one of the most gifted pirates too. Go Wolfie.

So… go. Steal. But make it yours

Warnings are the new test failures 3

Posted by Piers Cawley Thu, 18 Dec 2008 16:10:00 GMT

Have you ever tried to run Rails, Rspec, Rake or, for that matter almost any Ruby library or application that you’ve ever heard of with the -w flag? How about running Rails with taint checking on?

They aren’t exactly pleasant experiences.

Meanwhile, over in Perl land, it’s a very rare module indeed that isn’t at least clean under -w and, where appropriate, taint friendly. It would be a very irresponsible Perl Monger indeed who wrote a web framework that didn’t assume it was going to be running under the -T flag. Warnings and taint checking are annoyances, and sometimes they’re flat out wrong, but more of the time they’re useful. Which is why, in Perl, you’ll sometimes see blocks of code like:

{
  no warnings;
  # Code that does stuff which would trigger a warning
}

If the author is being particularly careful, she will specify which warnings to suppress – after all, there’s no need to turn off all the warnings if all you’re intending to do is redefine a method. So the prudent Perl programmer would write:

{
  no warnings 'redefine';
  # Code that redefines an existing method
}

However, there are often ways of achieving your aim even with all the warnings on.

If modules that don’t have use warnings are rare on CPAN, modules that don’t have use strict will get the unwary programmer laughed at in the street. There are modules that simply won’t work under use strict, but they tend to have no strict, either wrapped around the narrowest scope that won’t work under strict, or proudly displayed up front. The presence of a no strict implies to the interested reader that the programmer knows (or thinks he knows) what he’s doing. Writing code that does even the most implausible metaprogramming things without raising errors from strict or spamming STDERR with warnings is a matter of professional pride. Writing straightforward code that stays silent is the absolute baseline for Perl programming professionalism in my book.

Meanwhile, here in Rubyworld, there’s no equivalent of strict and it’s actively hard to start coding with warnings turned on because important frameworks like rspec and rails aren’t -w clean. In Perl, this isn’t a problem, use warnings turns warnings on lexically. Your code might well call all sorts of noisy code elsewhere but, unless you’re running with -w as well, you’ll only see the warnings for your code. If you set $VERBOSE, you’ll get all the warnings. Warnings in the log file should be like red Fs in your test output – a sign that all is not as good as it could be in your code. Sure you could just ignore the ones you know are harmless, then you’re in danger of losing the real problems in the noise.

As a gesture of goodwill, here’s alias_method_chain written so it should raise no warnings except when the ‘without’ method already exists.


def alias_method_chain(target, feature)
  aliased_target, punctuation = target.to_s.sub(/([?!=])$/, ''), $1
  yield(aliased_target, punctuation) if block_given?

  with_method, without_method = "#{aliased_target}_with_#{feature}#{punctuation", "#{aliased_target}_without_#{feature}#{punctuation}" 

  alias_method without_method, target
  remove_method target # Warning begone!
  alias_method target, with_method

  case
  when public_method_defined?(without_method)
    public target
  when protected_method_defined?(without_method)
    protected target
  when private_method_defined?(without_method)
    private_target
  end
end

Maybe time to look at shoulda 1

Posted by Piers Cawley Thu, 11 Dec 2008 12:24:00 GMT

So, because I’m sure that there’s a better way of drying up my rails apps, I’ve been porting Magritte to Ruby (given a good metadescription of your models and judicious application of the visitor and interpreter patterns, it’s amazing what you can do). Now, Magritte comes with a pretty decent test suite in its Smalltalk box. However, that test suite makes serious use of inheritance. Several tests of the leaf classes in the Magritte description hierarchy define maybe three helper methods which parametrise the tests they inherit from their parent test suites.

It’s all very clever (but in a good way), but it’s a bugger to implement in Rspec. I’ve been reduced to writing a shared behaviours file with lots of blocks that look like:

shared_examples_for "MetaDesc::Base" do
  ...
end

shared_examples_for "MetaDesc::Description" do
  ...
  it_should_behave_like "MetaDesc::Base" 
end

shared_examples_for "MetaDesc::ElementDescription" do
  ...
  it_should_behave_like "MetaDesc::Description
end

Essentially, I’m stitching together an inheritance hierarchy by hand.

Maybe it’s time to go back to Test::Unit and maybe to try shoulda

I’ll keep you posted on how the Magritte port’s going. Next step after the basic port is to write a visitor to generate an ActiveRecord schema I think, but I might end up writing some kind of Pidgin for describing objects first – depends how much of pain it is to roll the descriptions objects by hand.

Javascript heresy 5

Posted by Piers Cawley Wed, 29 Oct 2008 13:16:00 GMT

So, remind me, what’s the rationale for always using the optional ; when you’re writing Javascript? The only reasons I can think of, off the top of my head are, “Because you’ll break minifiers without it” and “Because Douglas Crockford doesn’t like it”. Well, broken minifiers that can’t parse the language correctly can kiss my fat hairy arse and argument from authority cuts little ice here.

Gareth Rushgrove pointed me at an article, which suggested that it’s because Javascript will insert a semicolon after the return in:

return
{ key: "value" }

But that’s not exactly surprising, and falls squarely into the “Don’t do that then” category of bugs, or putting it another way, the Dominus Doctrine (“You can’t just make shit up and expect the computer to know what you mean, retardo!”) applies.

Ruby also has an optional semicolon, but good style is avoid using them and we seem to survive. In fact, the Ruby parser is rather less capable than Javascript’s:

jQuery('.class')
  .addClass('whatever')
  .html('New inner HTML')

is legal Javascript, but, in Ruby you have to write:

jQuery('.class') \
  .addClass('whatever') \
  .html('New inner HTML')

because if you don’t the compiler throws its toys out of the pram and, for bonus points, the resulting parse error implies that the parser knows what you meant but decided to throw the error anyway. Ho hum.

Is there something I’ve missed? Or should I make a preemptive stand against incompetent minifiers and start writing my Javascript without semicolons?

Updates

In the comments, “James” offers a succinct piece of code using Prototype that demonstrates the problem rather neatly. In the absence of semicolons, code like:

var foo = 3
, bar = 2 + foo

[foo, bar].each(function (i) { console.log(i) })

gets parsed as

var foo = 3
, bar = 2 + foo[foo, bar].each(...)

Which isn’t exactly what you want. If I were feeling churlish, I might argue that such problems are one reason why the jQueryish way:

var foo = 3
, bar = 2 + foo
$.each([foo, bar], function () {...})

is a better way of iterating over things, but I’m not entirely sure that it is.

Looks like I’ll keep taking the semicolons.

I think I'm in love with an Axe

Posted by Piers Cawley Mon, 29 Sep 2008 06:04:00 GMT

We’ve just spent the weekend on one of Robin Wood’s spoon carving workshops, which was my 41st birthday present from Gill. It was great fun, if a little tiring. There is something primally satisfying about turning a piece of wood into woodchips. Getting a spoon or spatula at the end of the process is a huge bonus. We came away with a bag full of more or less decent treen, a couple of woodcarving knives and a burning desire to own one of Robin’s small drinking vessels.

Oh. And I fell in love with an Axe. The Gränsfors Bruks Swedish Carving Axe to be precise. This is the tool you use for turning a log into a spoon blank, and for much of the rough shaping of that blank. During the course of the weekend, I tried both the Gränsfors axe and an English ‘Kent pattern’ axe of the sort that can be picked up at car boot sales for pennies and sharpened and rehandled easily (quite what you use to rough out the new handle is left as an exercise to the interested reader). The English axe was very nice, but the Swedish one was just lovely. In particular, there’s a move which involves gripping the handle right by the head and flicking your wrist. This takes the top half of the blade through the wood in a precise sweeping motion that slices off wood in a way that’s almost erotically satisfying.

Yup. I don’t get out much. Why do you ask?

My choice lies before me: an English blade for maybe a fiver from a car boot sale or a sultry Swedish beauty for seventy quid from gransfors.co.uk? It’s not even a choice. The Swedish beauty had me at ‘car boot sale’ – I’m not sure which circle of hell car boot sales belong in, but I’m certain I don’t want want to go there. Besides, I’m a photographer and a computer programmer. Most of the bits and pieces cost hundreds or thousands of pounds.

Now, where did I put my credit card?

Just a thought

Posted by Piers Cawley Fri, 26 Sep 2008 04:46:00 GMT

There’s a refactoring principle that states that, when you start doing the same thing for the third time, you should refactor to remove the duplication.

I’m starting to wonder if there’s a Smalltalk principle which states that, when you start doing the same thing the second time, you should search the image for the obviously named method (or use the method finder to find some candidate by feeding it some inputs and an expected answer), because the odds are good that it’s only the second time for you – it might be the millionth time for the image you’re working in.

And if there were, what then? 19

Posted by Piers Cawley Sat, 20 Sep 2008 06:58:00 GMT

The Alpha Course people have been running a bunch of poster ads built around the slogan “If God did exist, what would you ask?”. The posters are filled with anodyne questions like “What’s the point?” or “Is this it?”.

They also tend to have large amounts of white space on them – I’m sure there are enterprising graffiti artists out there who look upon that as a fine opportunity.

So, here’s a few questions I’d ask god, if it existed:

What about that malaria parasite?

Because nothing says boundless Love like cooking up a disease that kills millions upon millions of people in the service of a parasitic lifecycle. Malaria’s been around so long that at some point during the long war between the parasite and humans, evolution cooked up a kink in the genome to try and keep the disease at bay. It works too. Sort of. Admittedly, if you get two copies of the gene, you get sickle cell anaemia, but malaria’s that awful that that bet seems worth making.

What’s the opportunity cost of religion?

Think about it. What proportion of humanity’s store of creativity, effort and money has been pissed up the wall in the service of religion over the years? Okay, so, the Sistine Chapel is a bit special, Bach’s Cantatas prod some serious buttock and it’s hugely good fun to sing from The Sacred Harp. But genius doesn’t go away if religion isn’t there. What would those artists have done, unshackled? And what might our scientists have done? The church has suppressed any number of scientific advances over the centuries and is still trying it on today. Look at the ongoing furore about stem cell research, cloning and all that other potentially good stuff.

Go to almost any place of worship and try to count the cost of it. It won’t be long ‘til you’re up to $lots. The money to pay for that comes off the backs of working people. For centuries, the tradition of tithing – giving 10% of your income to the church – wasn’t just a tradition, it was The Law. 10% of everything you earned, grew, made. For what? What might free people have achieved given that money and time to use as they saw fit?

Hitler, Pol Pot, Stalin, The Spanish Inquisition, Conquistadors… why?

Religious apologists would have you believe that the first three of those are proof of the awfulness of atheism. But they built their power and performed their atrocities by harnessing up the same religious impulses that gave us the Spanish Inquisition and the conquistadors. The religious impulse says “We are the Right People, they are savages”. Once you’ve got people convinced that they’re on the right side of the fence, it’s amazing what they’ll do to others in the name of a loving god.

If god exists, why were these people even born? You can tell me that god works in mysterious ways its wonders to perform, but I don’t really see how you can call genocide a ‘wonder’. If god’s going to claim to be the source of morality, then surely it should be held to those same standards. If god exists, then it has the power to stop atrocities. The fact that they happen leads me to infer that either there is no god, or any existing god is malevolent.

What’s wrong with women?

Look at almost any holy book you care to name, and women usually end up holding the smelly end of the stick. It may well be that sexism is endemic in human nature (I don’t think it is mind), but when you have religious authority for treating women as chattels, keeping them barefoot and pregnant and generally treating them as second class citizens… Well, it doesn’t help does it? Most of the holy books seems to have a pretty low opinion of men’s ability to keep it in their pants too. Otherwise why all the idiotic strictures about women keeping themselves covered up lest they inflame the uncontrollable desires of men. Come on! Blaming the victim’s so medieval.

Why should I worship you?

So, god made me. Big fucking deal. In the words of every teenager ever: I didn’t ask to be born. I owe god nothing. If I did want to worship my creator then I’d be far more inclined to worship my mother; I know she exists, and she went to a great deal more trouble to bring me into the world than anyone or any thing else that I can think of.

How do we get rid of you?

Seriously. God’s nothing but trouble. The suffering in the world’s dreadful when you stop to think about it. If we can lay the blame at the door of the cold, implacable machine that is Darwinian evolution, then there’s comfort in knowing that it’s nothing personal. It’s just the way the chips have fallen. There’s comfort too in knowing that there’s nothing to stop us as individuals and as a wider community doing everything in our power to make the world a better place for us, our children and the 8 billion other folks we’re sharing the place with. Because this is it. This is our only go on the merry go round. There’s no heaven, no hell, there’s just the world we make for ourselves and pass on to the next lot. It’s in our own best interests to look after it.

But if you have to lay the blame for the bad stuff at the door of some god, some conscious being who deliberately did this… It’s intolerable, frankly. That some being could choose to unleash malaria, TB, bubonic plague, syphilis, AIDS and the common cold on the world that it created is just… When we catch kids pulling the wings off flies, we tell ‘em off. When we catch god doing worse things, we (or a depressingly large fraction of us) worship the bloody thing. And because we buy the promise of a better world to come, we do a crappy job of making the world we’re in a better place. Great.

Does god exist?

I’m an atheist. I doubt anyone could prove, absolutely, the nonexistence of god. However, I fervently hope that there is no god because the alternative is so awful.

Arguments you wouldn't make in Alabama 11

Posted by Piers Cawley Mon, 15 Sep 2008 09:06:00 GMT

I spent the weekend at the UK Sacred Harp Convention, singing blood curdling hymns to the glory of god, very loudly with a hundred or so others. Great fun so it was. There’s something joyous about hollering out a hymn that opens with the line “And am I born to die?” and ends with the stanza

Waked by the trumpet’s sound
I from my grave shall rise
And see the Judge in glory crowned
And see the flaming skies

Especially if you’re stood in the middle of a hollow square with the altos behind you hitting a high note that lifts every hair on the back of you neck.

Anyhow, at one point during the Saturday evening social I found myself arguing that, although we singers today may feel grateful to those congregations of singers down the years who have sung these songs and handed the practice down to succeeding generations, there’s no requirement to be grateful, or even to go hunting for ‘authenticity’. Every generation that’s sung these songs and many others haven’t sung them to preserve them or to pass them on. They’ve sung them because the act of singing them has helped them to get through their lives. The songs we have, we know because successive generations have found them to be worth singing or recording. And we sing them for similar reasons. Future generations can go hang, I sing this stuff because it makes me feel good, not because I have some kind of duty.

“It’s a Darwinian argument,” I said, “Though obviously, I wouldn’t put it like that in Alabama…”

If you're going to add a hook, make it a big one 10

Posted by Piers Cawley Mon, 08 Sep 2008 06:11:00 GMT

Jay Fields responds to on Ola Bini’s Evil Hook Methods? about the common ruby idiom that lets us write:

class Fruit
  include DataMapper::Resource
  property :id, Integer, :serial => true
  property :name, String
  property :notes, Text, :lazy => false
end

What Ola and Jay don’t like about that is the way that a single include DataMapper::Resource actually adds class methods to Fruit because the implementation of DataMapper::Resource.included looks like:

module DataMapper::Resource
  def included(module)
    module.send :include, InstanceMethods
    module.send :extend, ClassMethods
  end
end

Which is a perfectly common idiom nowadays, but which breaks include’s contract in annoying ways. Jay proposes fixing this by adding a become method to Object which would wrap the include and extend in such away that they’d be called by the including class. Huzzah. And it makes sense… sort of. But it really doesn’t go far enough.

Let’s take another look at the original code snippet shall we? The thing that I notice is the wide scope of that ‘property’ method. It really isn’t needed anywhere except for defining how a Fruit is mapped onto the database. What happens if we take a leaf out of Perl’s book:

class Fruit
  use DataMapper::Resource {
    property :id, Integer, :serial => true
    property :name, String
    property :notes, Text, :lazy => false
  }
  property :foo # => raises an exception
end

The block gives our extending module somewhere to play, it can introduce a full on domain specific pidgin for the duration of the block with no fear of polluting the including class with anything but the methods its contracted to provide. So, how do we implement use. Something like the following should serve the purpose:

class Module
  def self.use(mod, *args, &block)
    mod.used_by(self, *args, &block)
  end

  def self.used_by(mod, *args, &block)
    if instance_behaviours || class_behaviours
      mod.become(self)
    else
      mod.send(:include, self)
    end
  end

  def self.become(mod)
    include mod.instance_behaviours) if mod.instance_behaviours
    extend mod.class_behaviours if mod.class_behaviours
  end

  def self.instance_behaviours
    nil
  end

  def self.class_behaviours
    nil
  end
end

The key idea here is that, in the default case, use will ignore all its arguments beyond the first and just include that module (a more robust implementation would probably ensure that an exception was raised if any extra arguments got passed). If the module author had written her module to comply with Jay’s proposed become, then we simply call become.

The interesting stuff happens when a module wants to do something a little more trick. So a version of DataMapper might do something like:

class DataMapper::Resource
  def self.used_by(mod, &block)
    mod.become build_behaviours(mod, &block)
  end
end

And build_behaviours would instance_eval the block with an object that would capture the properties and use them to build a set of class and instance methods appropriate to the description.

Another module might simply take a hash to describe how things should be parameterized. It all depends on the needs of the module being used. The aim being to avoid polluting the caller’s namespace any more than necessary. If I use a DataMapper type package, then all I want to end up with in my client classes are appropriate instance accessor methods, I don’t need spare class methods like property or storage_names that are only of any use when I’m describing my class.

Updates

I edited one of the code snippets to remove a particularly heinous piece of brace matching. Thanks to Giles Bowkett for the catch. Also edited another snippet to make it into real ruby rather than some bastard combination of Ruby and Perl. Thanks to Yossef for that catch.

Oh. Bugger 2

Posted by Piers Cawley Mon, 01 Sep 2008 08:48:00 GMT

If you asked me to name my favourite radio and TV comedy, the odds are very good that Geoffrey Perkins had a hand in most of them. When I found his obituary in this morning’s Guardian I felt almost physically winded. I never met him, I don’t know anyone who did, but he was someone who helped to make the world a pleasanter place to be in. My thoughts are with his family and friends, who are no doubt even more gutted than I am.

Older posts: 1 2 3 ... 30



Just A Summary