2011-11-30

The Code-Off

The other day my team arranged a little code-off. A little programming contest. It was set up as a competition, where our team of four developers was divided into two sub-teams.

For the contest, I had found a class in our codebase functioning as a controller, that we would have to edit in relation to features we would be adding in the near future. We already had three similar features, added incrementally without really doing any cleanups afterwards, and we were going to add three more features that would behave in a the same or like manner. Here is a quick-look of the relevant parts of the class (totally obfuscated, of course.)
class Foo {
public:
  // detailes omitted
  Foo(/*contextual arguments*/);

  Bar * addKindA();
  Bar * addKindB();
  Bar * addKindC();

private:
  void addBar(Bar * b); // side-effect, called from the adders.
};
Following this pattern, the three next features would make the class look something like the following. Not exactly a maintainable class with low coupling:
class Foo {
public: // detailes omitted Foo(/*contextual arguments*/); Bar * addKindA(); Bar * addKindB(); Bar * addKindC(); Bar * addKindD(); Bar * addKindE(); Bar * addKindF(); private: void addBar(Bar * b); // side-effect, called from adders. };
We wanted to apply the open-closed principle on this class, so that we would not have to edit this particular class when adding the new features and instead provide extension-points for them. The mission for our code-off was thus: Within three hours, implement a solution that closes the class for edits w.r.t the planned features. Then we scheduled an hour afterwards, for discussion of the two resulting designs and choosing a winner. The winner then got the honor of being integrated in to the codebase.

One of the main goals with this "competition", was to give all on the team a practical experience with applying the open-closed principle in a real-life working scenario, as well as simplifying and lessen the chance of introducing errors to this class when adding the mentioned features later on.

The resulting designs was not to different - there are only in so many ways a class with three factory functions returning the same type can be closed from adding a new factory function. The "winning" design was able to isolate the Foo object from the details of object creation, conceptually looking like this:
class Factory {
virtual Bar * createKind(string kind) = 0; }; class Foo { public: // details omitted Foo(Factory * f, /* contextual arguments */); void addKind(string kindname){ Bar * b = f->createKind(kindname); addBar(b); } private: void addBar(Bar * b); };
With a superficial glance to the problem, the Factory argument to Foo's constructor might seem sub-optimal, but suffice it to say here that the objects created by the factory and the Foo object it self are bound by an external context that makes this binding required. The design we chose is really not the interesting part to talk about either.

The interesting parts was what else we learned in such a short time. In an intense competitive "get this done in 3 hours" setting, some important impediments got really visible:
  • Building the software took time - disrupting flow, and impeding progress.
  • Unittests that tested more than the unit (e.g. becoming integration tests) became a stumbling block (The test of the Foo class was strongly coupled to some of the concrete subclasses of Bar, and even tested it's behavior. This caused the refactoring to become painful and difficult.)
  • Lack of communication while pairing - contributing factor to not having a working solution in the end.
  • Making mock-objects for objects that inherits from QObject is actually a PITA.
These impediments made us spend more time "mucking about", than actually designing and implementing. We knew about them, of course, but this very short sprint made them so visible, that us actually doing something about them are more probable.

Finally: The code-off have a wanted side-effect. There is no doubt in the team, where the design of that particular class (and it's immediate surroundings) is going, reducing the cost when designing and implementing the next similar features.

The initial goals were achieved, we learned a lot just from this little four hours exercice. The ROI is definitely positive. We'll do it again.

There are several things that lends it self to "competition-form"; small refactorings like discussed herein, entire design spikes, UI design mockups and through to implementing an entire feature. I will be doing more of this in the future.

2011-07-20

Reflection by introspective frontal lobotimization in D





Many of the widely used languages of today have built in runtime
reflection. From the top of my head i can mention Java, Python, Ruby,
C#, Lua, SmallTalk - popular languages with reflection mechanisms,
that allow you to inspect objects at runtime and call methods based on
name-lookups. Even C++ can get some reflection mechanisms when
used together with Qt and parsed with the moc. D on the other hand,
does not have reflection. And the first day - or was it the second - I
tinkered with D, I wanted to write something that would naturally call
for reflecion had I written it in, say Python.

D does however have something that the other already mentioned
languages does not have: A very powerful compile time code generation
and inclusion mechanism, the mixin. AFAIKU probably only surpassed by
the macro capabilities featured by common lisp. A quote from
Alexandrescus book, The D Programming Language, (p.47) seems fitting:
"If expressions were various kinds of screwdrivers, mixin would be a
power screwdriver with exchangeable heads, adjustable clutch, a brain
surgery adapter, built in wireless camera, and speech recognition." D
runs a full-fledged interpreter during compilation, which enables you
to write D code that generates D code, and have it executed during
compilation in order to compile in the code generated from it as part
of your program. Awsomeness. It's so powerful it makes me go all
GEB. Mixins allows you to fill a really nice bag of both tricks and
treats and this blog post is about how to exploit them together with
the compile-time inspection mechanisms in D, in order to create a rude
form of reflection so as to look up and call objects function based on
its name.

Lets say I have a class Foo as follows:

class Foo {
  void callOne(){
  }
  void callTwo(){
  }
  void dontCallMe(){
  }
}

I want to extract a subset of these, say all that have names that
begin with "call", and build a collection of callables that enables me
to call them when I have an Foo instance. Using a mixin, I could for
example compile in the following code:

mixin("static function(Foo)[] functions = 
    [function(F f){ f.callOne(); },
     function(F f){ f.callTwo(); }]");

The 'functions' array is added to what ever scope the mixin reside
in. Unfortunately, this is not in it's entirety deducible compile-time
by the D-compiler (known bug). But that doesn't matter, there is a
simple workaround - write static function wrappers and add these to
the function table, instead of anonymous functions. The following
little expansion compiles and do exactly that.

mixin("
  static void callOne(Foo f){
    f.callOne();
  }

  static void callTwo(Foo f){
    f.callTwo();
  }

  static function(Foo)[] functions = {&callOne, &callTwo};");

Now I have an array with two functions, that allows me to call the
wanted functions just through indexing in this manner:

Foo f = new Foo;
functions[0](f); // calls f.callOne()
functions[1](f); // calls f.callTwo()

Now we need only two things: Something to deduce the functions we
should wrap in this manner while compiling, and something to generate
the code we need for those functions. Lets do the code generating
first - this is where the magic is.

string generateFunctionTables(string[] names){
    string res = "";
    foreach(name; names){
      res ~= "static " ~ name ~ "(T t){ t." ~name ~ "();}\n";
    }
    res ~= "static void function(T)[] callFunctions = [";
    foreach(name; names){
      res ~= "&"~name~",";
    }
    res ~="];";
    return res;
}

mixin(genereateFunctionTable(["callOne", "callTwo"]));

While compiling, the included D-interpreter kicks in and call
generateFunctionTable during compilation, and build the code we want
depending on the input array of function names (and, I might mention,
it give fairly sensible compile-time errors if the function names supplied
are wrong.)

The final part is next to trivial - there are introspection mechanisms
available at compile-time, that allows listing all functions on a type,
and maybe match them with a string prefix:

string[] enlistFunctions(){
  string[] res;
  foreach(func; __traits(allMembers, Foo)){
    if(func.indexOf("call") == 0){
      res ~= func;
    }
  }
  return res;
}

This function can be called during compilation, and the results can be
used as arguments to our already defined code generator. We get the
table we want, simply by using this line:

mixin(genereateFunctionTable(enlistFunctions()));

So far, We've only known about the class Foo, so this is not very
general. Wrapping it in a templated scope improves things a bit. The
final code looks like this:

import std.stdio;
import std.array;
import std.string;

class Foo{
  void callOne(){
    writeln("One Called");
  }
  void callTwo(){
    writeln("Two called");
  }
  
  void dontCallMe(){
    assert(false);
  }
};

template NamedFunctions(T, string prefix = "call"){

  string buildStaticFunctionWrappers(string[] names){
    string res = "";
    foreach(name; names){
      res ~= "static " ~ name ~ "(T t){ t." ~name ~ "();}\n";
    }
    res ~= "static void function(T)[] callFunctions = [";
    foreach(name; names){
      res ~= "&"~name~",";
    }
    res ~="];";
    return res;
  }

  string[] enlistFunctions(){
    string[] res;
    foreach(func; __traits(allMembers, T)){
      if(func.indexOf(prefix) == 0){
        res ~= func;
      }
    }
    return res;
  }

  mixin(buildStaticFunctionWrappers(enlistFunctions()));
  static string[] functionNames = enlistFunctions();
}

int main(){
  Foo f = new Foo;
  foreach(idx; 0..NamedFunctions!Foo.functionNames.length){
    writeln("\nExecuting:" ~ NamedFunctions!Foo.functionNames[idx]);
    NamedFunctions!Foo.callFunctions[idx](f);
  }
  return 0;
}

In order to make it a bit more general I've wrapped it in a
parameterized scope, parameterized on the type of the object and a
matching string for the functions. In addition I added the name-table
so that I can match function with function name (I was unable to
generate a name-function map during compilation, the compiler frowned,
but this structure give me what I want indirectly. The name-function
map can be constructed runtime though.)

The output is as follows:

banach:Source rolvseehuus$ ./reflect

Executing:callOne
One Called

Executing:callTwo
Two called

In summary, I've demonstrated how to use compile time introspection
and mixins in order to extract certain functions from a class based on
a naming convention, enabling code to indirectly identify these
functions by a name-lookup that can be extended to a reflection
database. It can be improved further, but it stands on it's own as an
example (I wish I had it a week ago.:) I can think of several places
where this might be useful - like when interfacing with other
languages, receiving messages from another process, or say - building
an xUnit-esque testing framework for D.