Archive for the ‘Programming’ Category

Chunk & Write

Tuesday, March 25th, 2008

Coders develop a style much like writers do. I’ll compare coding to writing prose again in the future. I don’t draw much distinction between the two.

Code has agreed upon conventions. I’ve read the phrase “don’t cuddle an else”, probably in a Perl style manual — Perl coders are style mavens.

But what does it mean? It means that:


if(it's_true) {
    say "yay, true!";
} else {
    say "yay, false!";
}

is stylistically worse than:


if(it's_true) {
    say "yay, true!";
}
else {
    say "yay, false!";
}

The difference is subtle but the rule makes sense. And it’s a structural sense that it makes. Code is easier to change when your else statements ride on their own line. That’s just a simple, logistical fact, and the assumption should consistently be that code is going to change.

Prose doesn’t have as strong an adherence to logistical efficiency. Sure, there are roundabout ways to say something, but that’s poetry and doesn’t lose style points unless it sucks. There’s bad code, too.

Calling it Even (Idempotence One)

Monday, March 24th, 2008

Idempotence in an operation exists when that operation may be exercised multiple times producing the same result. There’s a bit more but that’s basically it.

When I code a module, often times there is a part of the module that loads information. For example, an initialization method might load data from a file or a database. I compare these types of operations to realizing you forgot something and having to drive to the store — this is very inefficient behavior though sometimes necessary.

Sometimes you end up (inadvertently, perhaps) calling the loader function more than once… Generally I do something like this:


# pseudocode!
class = new Class() {
  function initialize() {
    i'm_not_loaded = true;
    load();
  }
  function load() {
    if i'm_not_loaded is true {
      load_me();
        i'm_not_loaded = false;
      }
  }
  function load_me() {
      do_lots_of_expensive_calculations();
      drive_to_the_store();
  }
}

class->load(); is functionally idempotent. The result is absolutely the same each time it is called. Note that if the load_me() function were written such that all of its expensive calculations had the same result each time they ran it would also be idempotent. What is interesting to me is that those expensive calculations (at the in-expense of a flag in memory) can not be run twice. This is an optimization, and while it is idempotent it does not replace something that is non-idempotent.

What’s idempotent in meatspace? Not much, it seems. Even if the result is the same the first billion times, the billion-and-first time might spark a total meltdown. Entropy is a bitch. Anyway I want to think about it some more. Ideas?

Abstraction Part Two

Monday, February 18th, 2008

You’ll perhaps remember the box kicking script from a few days ago. That kick was the result of a series of finite steps. As I chained them together they looked like a relatively smooth move (for an ex-lax). Let’s say I have another action I want boxy to perform. I’d be stuck scripting it up mostly from scratch. Sure, I’d be able to cut and paste, but all of the heavy lifting I did before would be tossed away. So why not make my own life easier?

Which parts of the kick are reusable and which are not? In order to figure this out I break out the work into pieces. In this case there’s all the chaining and the moving boxy around nonsense, and then there’s the description of how it moves. If I’m lucky, next time I want to move boxy I only need tell it where to move, and not how it should go about moving. Enter my base animation class:


Animate = new Class({
    options: {
            defDur: 200
    },
    initialize: function(el){
            this.target = el;
            this.d = [];
            this.t = [];
    },
    run: function(d, t){
         var tfx = new Fx.Styles(this.target, {
                 wait: false,
                 transition: Fx.Transitions.Quad.easeOut
         });
         var n = 0;
         var dly = 0;
         this.t.each(function(tarr) {
                 if(this.d[n] != null) { dur = this.d[n]; }
                 else { dur = this.options.defDur }
                 tfx.options.duration = dur;
                 tfx.start.delay(dly, tfx, tarr);
                 dly += dur;
                 n++;
         }.bind(this));
     }
});
Animate.implement(new Options, new Events);

I will spare you the details of the Mootools syntax here. This class allows me to specify a list of instructions for boxy. I can then extend the base behavior with different instruction sets, making further actions a snap! The boxes blow are all scripted into subclasses of my Animate class. (Again, sparing details…) The first is the good ol’ kick. The second is a scripted random series of steps. It will always be the same. The third is an unspecified set of 40 randomly generated movements. Go ahead, give em a shot!

For those brave and/or interested souls, here’s the third random extension of the base Animation class, which I’ve called Butterfly. Butterfly took me about a sixth of the time to script that the original Kick did.


Butterfly = Animate.extend({
        options:{
                min: 20,
                max: 300
        },
        initialize: function(el, steps){
                this.parent(el);
                for(i = 0; i < steps; i++){
                        this.t.push({
                            'top': this.next(),
                            'left': this.next()
                        });
                }
        },
        next: function() {
                return Math.floor((
                         this.options.max
                         -(this.options.min-1))
                         *Math.random())
                         + this.options.min;
        }
});

Abstraction Part One

Tuesday, January 29th, 2008

Abstraction is a reduction of scope. When approaching a problem, we hopefully paint a large picture and quickly expand that picture into a series of finite steps. Much like computer instructions our tasks are finite and concrete*, whether those tasks are building an application or typing the letter ‘f’. Abstraction comes in at the optimal instruction scope and flattens some of the necessary steps, reducing the overall scope. For example: while typing the letter ‘f’ has an extremely small scope, and building an application is scopious, abstracting away an IPC** method has just about the correct scope.

Abstraction helps me to build a support structure for my code. It helps me to reuse things rather than rewrite them. And sometimes I don’t do it and I write something quick that I’ll later rewrite or throw away. When I do that I can hear a baby cry in the distance.

Next time I bring up abstraction I’ll produce some code. This is only an introduction.

* Humans persist on a looser timeline than computers and are known to eschew order rather than demand it.
** Inter-Process Communication. Many processes would have to talk to one central ear, for example. They’d all have to do it in the same way so you abstract and write the talking part once. Otherwise you might fat finger one process and later discover it talking to the central hand.