[ Content | View menu ]

Make extension points objects

Written on 14 Aug 2005

In his most recent blog entry, Martin Fowler writes about the problems of requiring people to call super. Absolutely! He uses jUnit setup and teardown as an example of where this hurts, we had exactly that problem in jMock, which makes our version of TestCase difficult to integrate for other people who want to do the same thing for their test frameworks. Java annotations might be an answer, but not for me since my current client is only just coming to terms with Java 1.4.

There’s another approach, as Ivan Moore pointed out, which is to replace inheritance with composition. What if the event was handled by a separate object? If TestCase had been split like this:

public class TestCase
  Test test;
  public void runBare() throws Throwable {
    test.setUp();
    try {
      test.run();
    }
    finally {
      test.tearDown();
    }
  }
}

where Test is an interface that defines the events in a test’s lifecycle. Now we have two objects: one concerned with the safe running of a test, and one concerned with the body of the test. Both are now focussed on doing just one job, and I can wrap the Test object with a decorator if I want to extend its behaviour.

Maybe the rule of thumb here is that if you want to add an extension point to your code, then no half measures: make it an object.

Filed in: Software culture.

One Comment

Comments closed

  1. Comment by Nat:

    Thanks Steve. This cut straight through a design problem I’d been wrestling with writing my own unit testing libraries in C# and recently in Python. Separating out the test itself from the object that manages test lifetime and that which catches and reports failures makes everything so much simpler.

    It just goes to show that applying the wrong pattern at the start can cause problems further down the line but also blinker your thinking about the problem. In this case the Composite pattern — making TestCase and TestSuite both be Tests — is the wrong thing to do.

    8 Nov 2005 @ 15:54