Wednesday, October 06, 2004

Logging into NT with Java

While researching JAAS I scratch-coded this interesting bit:

final String name = "Bob the Builder";
final LoginContext context = new LoginContext(name, null, null, getNTConfiguration(name));

context.login();
context.logout();

Of course, the secret is in getNTConfiguration:

static Configuration getNTConfiguration(final String name) {
    final Map options
            = new HashMap() {
        {
            put("debug", "true");
            put("debugNative", "true");
        }
    };

    final AppConfigurationEntry[] appConfigurationEntry
            = new AppConfigurationEntry[]{
        new AppConfigurationEntry(NT_LOGIN_MODULE_NAME, REQUIRED, options),
    };

    final Map entries
            = new HashMap() {
        {
            put(name, appConfigurationEntry);
        }
    };

    return new Configuration() {
        public AppConfigurationEntry[] getAppConfigurationEntry(final String name) {
            return entries.get(name);
        }

        public void refresh() { }
    };
}

And the super-secret is the value of NT_LOGIN_MODULE_NAME: "com.sun.security.auth.module.NTLoginModule".

The output when I run using all the debug options is:

An attempt was made to reference a token that does not exist.
		[NTLoginModule] succeeded importing info: 
			user name = boxley
			user SID = S-1-5-21-123456789-839522115-1060284298-38670
			user domain = MYDOMAIN
			user domain SID = S-1-5-21-123456789-839522115-1060284298
			user primary group = S-1-5-21-123456789-839522115-1060284298-513
			user group = S-1-1-0
			user group = S-1-5-32-544
			user group = S-1-5-32-545
			user group = S-1-5-4
			user group = S-1-5-11
			user group = S-1-5-5-0-77027
			user group = S-1-2-0
			impersonation token = 7120
		[NTLoginModule] completed logout processing
getting access token
  [getToken] OpenThreadToken error [1008]:   [getToken] got user access token
getting user info
  [getUser] Got TokenUser info
  [getUser] userName: boxley, domainName = MYDOMAIN
  [getUser] userSid: S-1-5-21-123456789-839522115-1060284298-38670
  [getUser] domainSid: S-1-5-21-123456789-839522115-1060284298
getting primary group
  [getPrimaryGroup] Got TokenPrimaryGroup info
  [getPrimaryGroup] primaryGroup: S-1-5-21-123456789-839522115-1060284298-513
getting supplementary groups
  [getGroups] Got TokenGroups info
  [getGroups] group 0: S-1-5-21-123456789-839522115-1060284298-513
  [getGroups] group 1: S-1-1-0
  [getGroups] group 2: S-1-5-32-544
  [getGroups] group 3: S-1-5-32-545
  [getGroups] group 4: S-1-5-4
  [getGroups] group 5: S-1-5-11
  [getGroups] group 6: S-1-5-5-0-77027
  [getGroups] group 7: S-1-2-0
getting impersonation token
  [getImpersonationToken] token = 7120

Friday, October 01, 2004

Upside-down inheritance

Here is a classic, persisted object in Java:

public class Foo extends Persisted {
    // fields

    // constructors

    // getters, setters
}

Pretty dull. What's wrong with that?

Now here's a typical query-by-example (QBE) method in some finder class (assuming something suitable like Hibernate or iBatis, and a supporting framework):

public Foo findFooByExample(Foo foo) {
    return (Foo) findByExample(FOO_TABLE, foo);
}

And here's a typical data transfer object (DTO) for passing around the found Foo to some other layer of the program:

public class FooData {
    // same fields as Foo

    // same constructors as Foo

    // same getters, setters as Foo
}

And then there's methods which take a Foo and need testing:

public void doBar(Foo foo) {
    // Does Bar look at anything in Persisted, or just Foo?
    // The test code needs to mock the persisted methods, if so.  Rats.
}

Oh, wait. Hrm. Lots of code duplication, lots of overhead to make changes, extra things to test. This is not looking so good. Why is that?

The inheritance is upside-down!

Once you disabuse yourself of the preconception that domain/database objects (DO) extend a persistence base class, the solution is trivial:

public class Foo {
    // fields

    // constructors

    // getters, setters
}

public class FooPersisted extends Foo implements Persisted {
    // fields, getters, setters for persistence
}

Now the QBE example uses Foo for input, and FooPersisted for output; FooData goes away completely; and the doBar method explictly requires either a Foo or a FooPersisted, making it clear if it does or does not fiddle with persistence.

And a bonus: it is almost always less work to implement the two or three fields and getter/setters which persistence uses rather than the larger number of fields which the DO uses. And as they are the same few fields everywhere, you can automate the process using code generation or annotations.

(Aside: Or course, it would be even easier still if Java only supported mixins. Then you just defined FooPersisted as:

public class FooPersisted extends Foo, Persisted {
    // empty -- no further code needed
}

No new keywords; no confusion—super always refers to the first class mentioned in the extends list.

But that is a different post.)

Safer collections

In my post on IndexMap I mentioned in passing SafeHashMap. What is that?

The JDK is very useful but has some warts. One of the worst is this inconsistency: if you try to index into a list with a non-existent index (i.e., beyond the end of the list) the collections throw IndexOutOfBoundsException. But what happens when you try to fetch from a map with a non-existent key? The JDK map implementations silent insert a null value into the map for you and return it. This leads to the following anti-idiom:

Value getValue(Map map, Key key) {
    return (Value) map.get(key);
}

See the problem? Now all code dealing with map anywhere in the program needs to test for null values and decide how to handle them, or else be happy with NullPointerException:

for (Iterator it = map.values().iterator(); it.hasNext(); ) {
    Value value = (Value) it.next();

    if (null == value)
        handleNullValue();
    else
        doTheRealWorkWhichIsTheWholePoint(value);
}

Try coding that 10 times real fast.

What is the solution? Force the correct idiom in the first code fragment:

Value getValue(Map map, Key key) {
    if (!map.containsKey(key))
        map.put(key, createMissingValue(key));

    return (Value) map.get(key);
}

And to enforce this idiom, extend a concrete class such as HashMap with a safe wrapper, hence SafeHashMap, and forbid missing keys or null inserts:

public Object get(Object key) {
    if (null == key) throw new NullPointerException();
    if (!containsKey(key)) throw new IllegalArgumentException();

    return super.get(key);
}

public Object put(Object key, Object value) {
    if (null == key) throw new NullPointerException();
    if (null == value) throw new NullPointerException();

    return super.put(key, value);
}

Friday, September 24, 2004

IndexMap

In my project there are several idiomatic uses of JDK collections. One is using Map to uniquely index domain objects by some field. The code is simple:

public class IndexMap extends SafeHashMap {
    public static interface Mapper {
        public Object getKeyFor(final Object value);
    }

    private final Mapper mapper;

    public IndexMap(final Class keyClass, final Class valueClass,
            final Mapper mapper) {
        super(keyClass, valueClass);

        this.mapper = mapper;
    }

    public IndexMap(final Class keyClass, final Class valueClass,
            final Mapper mapper, final Collection values) {
        this(keyClass, valueClass, mapper);

        addAll(values);
    }

    public void add(final Object value) {
        put(mapper.getKeyFor(value), value);
    }

    public void addAll(final Collection values) {
        for (final Iterator it = values.iterator(); it.hasNext();)
            add(it.next());
    }
}

(SafeHashMap is another JDK collection extension. It forbids null keys and values, and requires they be of certain classes.)

Idiomatic use looks like:

new IndexMap(KeyType.class, DomainType.class, new IndexMap.Mapper() {
    public Object getKeyFor(final Object value) {
        return ((DomainType) value).getKey();
    }
}, initialValues);

Which indexes a collection of DomainType domain objects by the key property.

UPDATE: Because of editing several files at once, I suffered a brain fart and mixed IndexMap (the point of this post) with AutoHashMap (another, still interesting collection).

Tuesday, September 21, 2004

Two ways to model tables in code

Generally I run into two ways to model tables in code.

The first way is to have a single object type respresenting a full row in a table, matching the SQL query SELECT * FROM TABLE. I'm going to call this way the model-the-table method. Every use of the table in code gets all fields regardless of need. This is wasteful but simpler to maintain.

The second way is to have several object types, each representing a single use of a row in the table, matching the SQL query SELECT COLUMN_1, COLUMN_2 FROM TABLE. I'm going to call this way the model-the-use method. Each use of the table in code gets only the fields needed. This is more precise but harder to maintain.

I'm undecided which I like better and have used both in projects, even within the same project. Perhaps enlightenment will come my way.

My pairmate, Karthik Chandrasekariah pointed out to me the similarity of this choice to using the Adapter pattern. Only instead of changing the view of an underlying code object with an adapter, you change the view of a database table.

Domain objects and compareTo

I wrote earlier about domain objects and boolean equals(Object) and how to handle primary keys. What about int compareTo(Object)? The same remarks about primary keys still apply, and the code pattern is:

public class Something implements Comparable {
    /* ... */

    public int compareTo(final Object o) {
        final Something that = (Something) o;
        int compareTo = firstPK.compareTo(that.firstPK);
        if (0 != compareTo) return compareTo;
        compareTo = secondPK.compareTo(that.secondPK);
        if (0 != compareTo) return compareTo;
        // ... likewise for other primary keys
        return lastPK.compareTo(that.lastPK);
    }
}

This sort of comparison method will group sorts by the order of comparison, so that firstPK groups together, then secondPK, etc.. If, say, you sorted [Apple, Blue], [Orange, Orange], [Apple, Red], this way, they would be grouped as [Apple, Blue], [Apple, Red], [Orange, Orange].

Layers and containers

I've been thinking about how J2EE containers work. They provide a world of many layers: application-container, container-Java libraries, Java libraries-byte code, byte code-JVM, JVM-platform libraries, platform libraries-native code, native code-OS, OS-hardware. (And there are, of course, calls from higher layers to lower layers even further down.) That's a lot of layers. I wonder what could be stripped out?

For example, Java handles thread scheduling for Java code, but the OS does the same for native code. How much are Java threads mapped onto native threads? (The answer varies quite a bit between platform and JVM implementation.) The same question arises comparing byte code to native CPU instructions. How much of a JVM could be performed directly by an OS?

There is plenty of research in these areas already (I was going to make a list of interesting links, but Google turned up so much, it hardly seems worth the effort—Google sure changes how research works), so I am looking forward to reading more about these ideas over time. Layers are good for abstraction, but over time the most successful abstractions become concrete and implementors take advantage to improve performance and transparancy. Witness pointers: C abstracted hardware addressing as pointers, which then C++ abstracted as virtual methods, which then Java abstracted as methods: success begats success.

I expect the same trend to continue as byte code slowly displaces native code and JVM-like things appear more in hardware and operating systems such as the cool work at Transmeta.

Saturday, September 18, 2004

Actor/Director

Fellow ThoughtWorker Andrew McCormick pointed out Actor/Director to me, a good pattern he coined. The simple example he casually posted was turning this:

public class TemplateMethodClass {
    public void doSomething() {
        setup();
        yourstuff();
        finish();
    }

    protected void yourStuff() {
    }
}

Into this:

public class DirectorClass {
    public void doSomething() {
        setup();
        Actor actor = getActorForYourStuff();
        finish();
      }

    protected Actor getActorForYourStuff() {
        // other possibilities
        // return new SingleActor();
        // return new MultipleActor(new SingleActor(), new SingleActor())
        return new NullActor();
    }
}

Seeing this, I immediately cleaned up a long-standing solution to the database connection problem, becoming:

public class ConnectionDirector {
    private final ConnectionProvider provider;
    private final ConnectionActor actor;

    public ConnectionDirector(final ConnectionProvider provider,
            final ConnectionActor actor) {
        this.provider = provider;
        this.actor = actor;
    }

    public void doSomething() {
        final Connection conn = provider.openConnection();
        try {
            actor.doSomething(conn);

        } finally {
            provider.closeConnection(conn);
        }
    }
}

Isn't that tidy? Both the connection provider and the connection actor are passed in. As Andrew noted, Dependency injection is probably the most important obvious-in-hindsight idea that's come along recently. And it fits perfectly into the Actor/Director pattern.

(Note to pattern mavens: does Actor/Director duplicate an existing pattern? I find the name to be very intuitive.)

UPDATE: Andrew later noted: Actor/Director is sort of a twist on Chain of Responsibility...or at least along the same lines. Both have the intent of separating what gets done from how it gets done.

Sunday, September 12, 2004

More on domain objects

Several excellent comments and communications asked me questions about my post on domain objects. There are several points I want to discuss further.

Why implement boolean equals(Object), and why compare only primary keys?
This is a the heart of equality v identity or object equality v instance equality. The basic complaint is why not just rely on identity as implemented in boolean Object.equals(Object)? Why not, indeed. Do not forget that even if you override equals, you can just call == yourself which cannot be overriden (in Java) and which always provides identity, not equality. But for domain behavior you really do want things to compare equal which behave identically. In fact, without this property all sorts of code becomes very tedious. Just try to implement an object cache without overriding equals.
Why mark primary keys as final?
This follows from using equality instead of identity for equals. If a primary key changes, the object is no longer the same. The primary keys are therefore immutable. If you want a new domain object, you must create a new instance with different primary keys.

The Program

I want a domain-specific language (DSL) in Java for domain objects. Were I writing in a more modern, flexible language such as Scheme (just an example; there are others), I would simply design a DSL for the problem of domain objects. As it is, Java forces an amalgam of coding conventions and extra-linguistic baggage such as XDoclet (equivalently, JDK 5 annotations with code generation) or AOP to accomplish the same task. I want to consider here the Java-only techniques for this goal.

Tuesday, September 07, 2004

A clever production v. testing trick

Say you have a database connection provider for production, and a mock persistence layer for testing. This setup is common for iBatis, Hibernate or similar solutions. How should you design the consumers of these? I fell upon this clever pattern today while reworking an event replayer which read events from a database and injected them into a messaging system:

/**
 * <code>Foo</code> does something clever. It has two
 * modes: production and testing.  For production, use {@link
 * #Foo(ConnectionProvider)} and pass in a provider.  For testing,
 * use {@link #Foo(BarMapper)} and pass in a mock mapper.
 *
 * The code takes great care in the constructors to ensure you cannot mix uses.
 * All instance variables are marked <code>final</code>.
 *
 * If you are in production use, the constructor tests <var>provider</var> and
 * assigns it, making the mapper <code>null</code>.  Then, if you try to use
 * the mapper instance variable directly instead of via the getter for it,
 * you will throw a <code>NullPointerException</code>.
 *
 * Contrariwise, if you are in testing use, the constructor tests the
 * mapper parameter and assigns it, making the provider <code>null</code>.
 * Then, if you try to use the provider instance variable directly instead of
 * via the getter for it, you will throw a <code>NullPointerException</code>.
 *
 * Lastly, there is no {@link Connection} instance variable.  Instead {@link
 * #barNone(Id)} gets one from the provider on the fly (the getter
 * ensure this only really does something if in production mode), and closes it
 * before the method returns.  There is never a leak, the connection is never
 * held for longer than needed, the method may be run more than once
 * statelessly, and the method uses a getter for the mapper, again ensuring
 * the code <cite>does the right thing</cite>.
 */
public class Foo {
    private final ConnectionProvider provider;
    private final BarMapper mapper;

    public Foo(final ConnectionProvider provider) {
        if (null == provider)
            throw new NullPointerException();

        this.provider = provider;
        this.mapper = null;
    }

    protected Foo(final BarMapper mapper) {
        if (null == mapper)
            throw new NullPointerException();

        this.provider = null;
        this.mapper = mapper;
    }

    public void barNone(final Id barId) {
        final Connection conn = getConnection();

        try {
            doSomethingCleverHere(barId, getMapper(conn));

        } finally {
            close(conn);
        }
    }

    private Connection getConnection() {
        return null != provider
            ? provider.getConnection()
            : null;
    }

    private void close(final Connection conn) {
        if (null != provider) provider.close(conn);
    }

    private BarMapper getMapper(final Connection conn) {
        return null != mapper
            ? mapper
            : new BarMapper(conn);
    }
}

See the idea? Several things are going on at once here. Read the class javadoc comment carefully. This trick will serve you well.

A footnote: why is the one constructor public and the other protected? Simple. The constructor taking a connection provider is for production and is marked public. The constuctor taking a mapper is for testing and is marked protected. Remember to keep production and test case code in the same package but in separate source trees.

Advice to persistence frameworks

In my previous post I described how to make good domain objects in Java. However, much of the advice is circumscribed by limitations in popular persistence layers below the domain objects. Therefore, I have some advice to persistence layer authors.

Support non-default constructors. Admittedly, this takes some cleverness. Say you have a class like this:

public class Foo {
    private final int count;
    private final int total;
    private int numberOfMonkeysInABarrel;

    public Foo(final int count, final int total) {
        this.count = count;
        this.total = total;
    }

    public int getPercentage() {
        return Math.round((float) (count * 100) / total);
    }

    public void setNumberOfMonkeysInABarrel(final int n) {
        numberOfMonkeysInABarrel = n;
    }

    public int getNumberOfMonkeysInABarrel() {
        return numberOfMonkeysInABarrel;
    }
}

A really clever persistence layer can work out what the inputs are for the constructor by noting the following:

  1. The Sun VM returns reflected fields in order of declaration. The documentation does not specify an order, however, so even though this is emprically true in JDK 1.4 and 5.0 VMs, this is a logically weak link.
  2. For given fields, filtering is easy to find just private final fields.
  3. By requiring than the order of inputs for a constructor match the ordering of fields (very common by convention), it is mechanical to match up constructor inputs to required fields, assuming required fields are declared private final.

And there you go: a persistence layer can create domain-safe instances without requiring an otherwise useless default constructor or getters and setters.

Saturday, September 04, 2004

How to make a domain object

There are several basic rules for designing a domain object. These rules keep safety and correctness in mind:

Always implement equals and hashCode
I have seen many memory leaks from inadvertent caches of domain objects which used object identity. When implementing equals and hashCode, only compare primary keys since that is the sense of equality the persistence layer uses.
Mark immutable fields final and provide no setters for them
Always mark primary keys final and only set them in a constructor. This means there is no default constructor.
Include all required fields in constructors
Never leave domain objects in an inconsistent state. The constructors should reflect this fact. Again that means no default constuctor.
Test the inputs of non-null fields
Simply provide if (null == someField) throw new NullPointerException(); in the constructor or setter which takes someField. If the field is not required, make the same check in the getter as it may have not been initialized yet.
Implement Comparable if there is a default sort order
Whenever domain objects have any kind of natural sort order, always implmement Comparable. Do not force other code to do the work on behalf of the domain object. And remember to compare as many fields as needed by the sort order. For example, a CustomerName comparator needs to sort on lastName, firstName, middleName and nameSuffix.
Implement toString for debugging
Do not use toString for business code or display. For those, use business-specific methods such as displayAs. Commons-lang provides an excellent ToStringBuilder for debugging.

Unfortunately, not all of them can be used with every project. For example, if you persist domain objects directly rather than using an intermediate persistence layer to represent database tables (e.g., Hibernate or iBatis), the framework requries that every instance field have a bean-like getter/setter. (Actually, recent Hibernate supports direct field access, but this is still uncommon with many projects.)

Tuesday, August 24, 2004

JUnit work around for lost exceptions

Here's the scenario: a unit test throws an uncaught exception, but then so does tearDown(). What happens? TestCase.runBare() says:

public void runBare() throws Throwable {
    setUp();
    try {
        runTest();
    } finally {
        tearDown();
    }
}

See the problem? If tearDown() throws, then runBare() loses any exception thrown by runTest() (which runs your unit test). [See the Java Language Specification, §11.3.] Rarely is this what you actually want since the lost exception was the original cause of test error. The solution—override runBare():

public void runBare() throws Throwable {
    Throwable thrown = null;

    setUp();

    try {
        runTest();

    } catch (final Throwable t) {
        thrown = t;

    } finally {
        try {
            tearDown();

            if (null != thrown) throw thrown;

        } catch (Throwable t) {
            if (null != thrown) throw thrown;
            else throw t;
        }
    }
}

The idea is simple. Store the exception from runTest() and rethrow it after running tearDown(). Make sure to throw any exception from tearDown() otherwise.

UPDATE: My brain finally caught up with my fingers and I realize that the sample solution is unnecessarily complex. Better is:

public void runBare()
        throws Throwable {
    Throwable thrown = null;

    setUp();

    try {
        runTest();

    } catch (final Throwable t) {
        thrown = t;

    } finally {
        try {
            tearDown();

        } finally {
            if (null != thrown) throw thrown;
        }
    }
}

Monday, August 23, 2004

Hidden static methods

While debugging some slow code with a programming partner, we ran across a long series of statements like this:

new Foo(args).run();

Line, after line like this. What is going on? Apparently the original writer was thinking of something like command pattern without any sense of do/undo/redo. But what he wrote instead is another anti-pattern. Rather than littering the VM with a series of use-once instances just to invoke a method on them, he could have said:

Foo.run(args);

And by using a static method have been more clear that this was functional, not object-oriented code. Not every problem is a nail requiring the same hammer.

Saturday, August 21, 2004

Turning 90 degrees

An interesting problem: you have a depth-first process and need to turn it into a breadth-first one. How to proceed? A simple publish-subscribe message bus works single-threaded so when a message receiver publishes a new message in response, the new message is processed before the rest of the receivers of the first message have a chance to run. This leads to some confusing situations where message order is counter-intuitive.

Since everything is plain Java, I cannot use continuations for the activation records else I would just reorder them. Ah, but I can come close enough for this simple system. Consider these two data structures (in reality, they are immutable classes, but I shortened them to C-style structs for conciseness):

public class Binding {
    public Receiver recipient; // the target object for Method.invoke(Object...)
    public Method onReceive; // the method
}

public class ActivationSet {
    public Set<Binding> bindings; // JDK 5.0, plain Set for JDK 1.3 or JDK 1.4
    public Message message; // the argument for on Method.invoke(Object...)
}

Now the publish algorithm is quite simple given an instance variable of Queue<ActivationSet> for the channel:

public void publish(Message message) {
    Set<Binding> bindings = findSubscribers(message);

    if (bindings.isEmtpy()) return;

    // Check if we're first to publish
    boolean topContext = activations.isEmpty();
    // Queue our recipients
    activations.offer(new ActivationSet(bindings, message));
    // Let the top context handle recipients in queue-order
    if (!topContext) return;

    while (!activations.isEmpty()) {
        // activate() invokes onReceive for each binding in the set
        activations.peek().activate();
        // Be careful not to remove our own activation set prematurely;
        // otherwise the topContext check above won't work right
        activations.remove();
    }
}

The effect is to queue up the depth-first nature of recursive method calls and handle them in breadth-first order. The code is quite simple once the concept is clear.

Wednesday, August 18, 2004

Smarter exceptions

Very commonly I see code which puts data into the message of an Exception as a way to pass information. This was certainly the case with the original Exception class which provided no way to hold context. Recent JDKs fixed that with Exception.getCause(). But I didn't realize the general usefulness of this approach until reading the changes so far in JDK5 Beta2. After all, exceptions are just classes; they too can have more methods. In fact, this is just what UnknownFormatConversionException.getConversion made me see. Useful information passed on an exception to aid in recovery, logging, etc. is just the ticket.

The switch statement

A nice post by Tom McQueeney on the new varargs feature in JDK5 marred by one point:

if (params.length > 0) lastName = params[0];
if (params.length > 1) firstName = params[1];
if (params.length > 2) middleName = params[2];
if (params.length > 3) nickName = params[3];

if (params.length > 4) {
    throw new IllegalArgumentException("Constructor called with too many arguments");
}

Why the series of if statements? A simple switch statement with fall-through is more clear:

switch (params.length) {
case 4: nickName = params[3];
case 3: middleName = params[2];
case 2: firstName = params[1];
case 1: lastName = params[0];
    break;
default:
    throw new IllegalArgumentException("Constructor called with too many arguments");
}

Tuesday, August 17, 2004

Two testing tales, one bad, one good

Tale one, package mismanagement

Here is an anti-pattern:

java/blarfage/Foo.java:

package blarfage; public class Foo { }

java/test/blarfage/FooTest.java:

package test.blarfage; import junit.framework.TestCase; public class FooTest extends TestCase { }

What is wrong here—where is the anti-pattern? Do not put test classes in a different package than that of the class under test. It looks clean and logical, but try it for a while and the pain of it hobbles your testing. Many useful tricks vanish, chief among them package-scope methods for tweaking the class under test. Don't just take my word for it: try it on any moderate-sized project and see for yourself.

Tale two, useful IoC trick

Here is a handy trick for configuring a class under test: provide a separate, protected constructor just for testing.

java/blarfage/Foo.java:

package blarfage; public class Foo { private final Bar favorite; public Bar(final Drink beer) { this(new Bar(beer)); } protected Bar(final Bar favorite) { this.favorite = favorite; } }

test/blarfage/FooTest.java:

package blarfage; import junit.framework.TestCase; public class FooTest extends TestCase { private TestFoo foo; protected void setUp() throws Exception { foo = new TestFoo(createMockBar()); } private static final TestFoo extends Foo { private TestFoo(final Bar favorite) { super(favorite); } } }

The idea is this: Say Bar is complex or expensive—java.sql.Connection is a good example. The public constructor takes the argument for constructing the private, expensive or complex object; the protected constructor takes the actual expensive or complex object so that a test can extend the class under test and use that protected constructor.

This trick is especially handy when you do not have control of code using the class under test (else you might refactor the public constructor to take the expensive or complex argument directly as the protected constructor does).

Wednesday, August 11, 2004

Brittle relations

Much of the time a project needs decoupling between a database schema and the business model using the schema. This setup uses some kind of mapping file, often XML, to glue the two pieces together. However as the schema evolves, mismatches between schema and business model show up at run-time during testing. This is very annoying. If a project does not need the looseness afforded by a separate mapping file, I have a different suggestion. The most common design in this scenario is to have a persistence layer for database work and a domain layer above that representing the business model.

Consider an intermediate third layer—call it the schema layer—between the persistence and domain layers. This schema layer uses the persistence layer to exactly model the database schema rather than the business model. The domain layer uses the schema layer rather than call the persistence layer directly.

Why the extra layer? With the extra schema layer the mapping file vanishes. Use tools to generate the schema layer automatically by interrogating the database during the build. Then, as the schema evolves, incompatible syntactic changes (changes in columns or types, not changes in meaning) propagate into the code of the schema layer and manifest themselves as compile errors in the domain layer. This is a great aid during development. Compile-time errors are much easier to catch automatically than problems during testing, and strange reflection contortions are kept out of the business model.

Tuesday, August 10, 2004

Supporting old code

One JDK5 feature I particularly appreciate is the simplicity of the new foreach syntax, and the addition of an Iterable<T> interface in support. However, much of the JDK was written before even Iterator was around such as StringTokenizer. What to do? Write a wrapper, of course:

/**
 * <code>EnumerationIterator</code> is an {@link Iterator} wrapper for {@link
 * Enumeration}. {@link #remove()} is unsupported.
 */
public class EnumerationIterator <T> implements Iterator<T> {
    private final Enumeration<T> enumeration;

    /**
     * Constructs a new <code>EnumerationIterator</code> from the given
     * <var>enumeration</var>.
     *
     * @param enumeration the enumeration
     */
    public EnumerationIterator(final Enumeration<T> enumeration) {
        this.enumeration = enumeration;
    }

    /**
     * {@inheritDoc}
     */
    public boolean hasNext() {
        return enumeration.hasMoreElements();
    }

    /**
     * {@inheritDoc}
     */
    public T next() {
        return enumeration.nextElement();
    }

    /**
     * {@inheritDoc}
     */
    public void remove() {
        throw new UnsupportedOperationException();
    }
}

/**
 * <code>EnumerationIterable</code> is an {@link Iterable} wrapper for {@link
 * Enumeration} to support JDK5 <em>foreach</em> syntax.
 */
public class EnumerationIterable <T> implements Iterable<T> {
    private final Enumeration enumeration;

    /**
     * Constructs a new <code>EnumerationIterable</code> for the given
     * <var>enumeration</var>.
     *
     * @param enumeration the enumeration
     */
    public EnumerationIterable(final Enumeration enumeration) {
        this.enumeration = enumeration;
    }

    /**
     * {@inheritDoc}
     */
    public Iterator<T> iterator() {
        return new EnumerationIterator<T>(enumeration);
    }
}

Now I can write this:

for (final String token : new EnumerationIterable<String>(new StringTokenizer("a:b:c", ":")))
    System.out.printnln(token);

Monday, August 09, 2004

Nice

Nice is a very attractive new Java-like language for the JVM. Xoltar has nice things to say about Nice, the language. I'm more than a little enchanted: much better type safety than Java, multimethods, closures, parametrics types, named parameters, tuples. Wow! And unlike Groovy, it really does look like Java after some weight-lifting. (I'm sorry, but I'm too attached to ;. Call me a "C" bigot, but it just looks wrong otherwise.)

I'm eager to give Nice a spin and perhaps use it a project. And the comparison of Nice and Groovy really isn't that fair — Nice is still pre-compiled into bytecode like Java, not scriptable like Groovy. There's plenty of need for both.

Trickiness with generics and reflection for methods

This caught me offguard at first:

public class Scratch { public static class Qux { } public static class SubQuux extends Qux { } public static class Foo <M extends Qux> { public void spam(final M meat) { } } public static class Bar extends Foo<SubQuux> { public void spam(final SubQuux meat) { } } public static void main(final String[] args) { try { for (final Method method : Bar.class.getMethods()) if ("spam".equals(method.getName())) System.out.println(method); } catch (Exception e) { e.printStackTrace(); } } }

So, just what does main print? The answer is fascinating:

public void Scratch$Bar.spam(Scratch$SubQuux) public volatile void Scratch$Bar.spam(Scratch$Qux)

Aha! Now I get it. Since the JDK5 compiler implements generics with type erasure, there needs to be a version of spam which takes the lowest possibly erased type, Qux, so that JDK1.4 runtimes can handle the method call. Crud. That messes up my reflection for messaging. However, the solution is staring right at me: volitile. Since there really is no such method as public void Scratch$Bar.spam(Scratch$Qux), the compiler synthesizes one and marks it as volitile. Nifty. Now I can filter those out with Modifier.isVolitile. No harm, no foul.