2011-08-19

Gross code: interleaved modes

I am tweaking some perl code.

It is gross.

Not because it's perl... sometimes I like perl. It's also not because it is code that interacts with a Microsoft SQL Server, although that certainly doesn't help.

No, it's gross because who ever wrote it decided that 'modes' were a good way to organize functionality, that arguments should mean totally different things in different modes, and that the implementation of each mode should be interleaved throughout the code using if/elsif constructs.

It looks a bit like this:

sub prepare {
  if ($mode =~ /^A/) {
    # Prepare A ...
  }
  elsif ($mode =~ /^B/) {
    # Prepare B ...
  }
}

sub do_work {
  if ($mode =~ /^A/) {
    # Do work A ...
    return $result;
  }
  elsif ($mode =~ /^B/) {
    # Do work B ...
    return $result;
  }
}

prepare();
do_work();

As a comparison, this is how I would structure the same logic:

sub do_job_A {
  # Prepare...
  # Do work...
  return $result;
}

sub do_job_B {
  # Prepare...
  # Do work
  return $result;
}

if ($mode eq 'A') {
  do_job_A();
}
elsif ($mode eq 'B') {
  do_job_B();
}

Note that my way is both a few lines shorter and quite a bit easier to comprehend. The difference is obvious even with only two modes of operation.

The code I am working with has about 20 modes.

It is GROSS.

But I'm still hacking on it, because it gets the job done.

Tags: tech


Recent posts

...