Simplest Thing that could possibly ... redux

heusserm on 2003-09-11T12:23:46

Ok, so here's the function:

sub RemoveSpaces
{
        my $s = shift;
        $s=~s/\s//g;
        return $s;
}


Here's the thing: This couldn't possibly break.

Does this mean that I don't need to test it, or at least I don't need to automate the testing of it?

One of the big elementes of XP and "well-factored" code is small sub-routines. Subs that are small enough that you can understand everything that is going on - or subs small enough to only need one comment, and that comment is the name of the sub.

In CS 611 (Software Engineering), we talked about collapsable code a lot. Basically, if you only have one return per function and don't have any knotted loops, it's possible to get complete code coverage of an entire function. If your next-level function does the same, you can abstract the lower-level function out and get code coverage of the higher function.

XP then provides two benefits:

1) Smaller systems have less complexity, and thus less bugs. XP emphasises keeping code small and simple.

2) Functions in XP stay small. There are less things that can break - examining a small portion of a chess board is much easier than trying to examine the entire board and all the possibilities. This leaves less things that can possible break.

And having less things that can possibly break is a very good thing.


Oh, the irony...

merlyn on 2003-09-11T13:54:50

sub RemoveSpaces
{
          my $s = shift;
              $s=~s/\s/g;
              return $s;
}
... Here's the thing: This couldn't possibly break.
And yet, it's invalid syntax. It is broken.

Test early, test often, test always.

Testing Enables Refactoring

chromatic on 2003-09-11T16:23:57

Though a test would catch that it doesn't compile (as Randal points out), it would also allow you to change it later to something like this:

sub RemoveSpaces
{
    my $s = shift;
    $s =~ tr/ \b\r\n\f//d;
    return $s;
}

It's okay if you don't want to do that, but I'd prefer it to the regex.

Re:Testing Enables Refactoring

pdcawley on 2003-09-14T06:58:32

Does that work in a Unicode world? The regex version does at least (one hopes) deal with all kinds of whitespace once and for all; the tr/// version is necessarily fragile because the programmer has to enumerate all possible kinds of white space.

Re:Testing Enables Refactoring

chromatic on 2003-09-14T07:29:45

You're right, it probably fails with Unicode. Thankfully, I don't have a story card for handling Unicode. :)

Re:Testing Enables Refactoring

pdcawley on 2003-09-14T22:24:56

Does anyone actually like Unicode?

breaking

gav on 2003-09-11T17:58:34

> Here's the thing: This couldn't possibly break



What happens if you get undef?