Dienstag, 9. Oktober 2012

Programming by Accident

Programming by accident is an anti pattern of software development. Until yesterday I thought it was obvious to avoid doing that - but I learnt that it's really easy to do it without event noticing. See how:
  1. Last week I was working on a small .net library. The AssemblyVersion in it was set to "1.2.0.*", because I did not really care about the revision number, and wanted to get rid of the responsibility to count it up manually.
    One day I left happy that my .net bridge was working as expected. When I resumed my work the next day, I made a small change, and ... the library did not even load. Instead I got "ole error 80131040".
    After what seemed an eternity of trying and googling I found that the library simply did not load, because the revision number was lower than the day before while the runtime was expecting the same revision or higher. According to the documentation the '*' in my AssemblyVersion was replaced by half the number of seconds since midnight. Well, that explained why it was lower than the day before...
    So, what was my mistake here? I was programming by accident, because I assumed I knew what the little asterisk was doing. And I had never looked into how .net works with the Assembly- and AssemblyFileVersions.
    The software had only looked like it was working correctly...

  2. In that library I made use of the shift operarator (<<). Hey, what can possibly go wrong with a shift? So, I made a loop that shifted a single bit through an integer until it was shifted out:
        int x = 0;
        do {
          y = 1 << x;
          Dostuff(y);
          x += 1;
        } while(y != 0);
    Well, turns out I created an infinite loop (disclaimer: I did not notice that initially, because the loop and conditions were actually a little more complicated than shown here; this example is quite constructed to show the underlying problem). The shift operator simply does not accept values that would shift all bits out; it does a secret '&31' and the shift distance. So when x hits 32 it actually does an 1<<0 again and y never turns 0.
    Again some programming by accident and also (I have to admit) a little bit of trying to be clever. Both tend to fall on your feet - and did.

Assuming a thing does what you think it does is programming by accident. And it can happen in the smallest of places...

Keine Kommentare:

Kommentar veröffentlichen