Monday, 30 November 2009

Code Dump: Stubbing with a map

A year or so back I wrote a cool little utility class MyInvocationHandler. This is used by simply creating a map of the proprieties and their values simply as I felt that:
Map backing = new HashMap();
backing.put("title", "ihaztehcodez");
backing.put("getURL",
            "ihaztehcodez.michael-lloyd-lee.me.uk");
Blog thisHereBlog = create(backing, Blog.class);

was easier on the eyes that the EasyMock styled
Blog thisHereBlog = createNiceMock(Blog.class);
expect(thisHereBlog.getTitle())
   .andReturn("ihaztehcodez").anyTimes();
expect(thisHereBlog.getURL())
    .andReturn("ihaztehcodez.michael-lloyd-lee.me.uk")
    .anyTimes();
replay(thisHereBlog);

However I was wrong to use either method. If I was to do so again I'd use write a BlogBuilder. It is a good chunk more work up front, but it leads to significantly better reading code.

Blog thisHereBlog = new BlogBuilder()
     .withTitle("ihaztehcodez")
     .withURL( "ihaztehcodez.michael-lloyd-lee.me.uk")
     .build();

This does mean I now have a mini project to start. Write a JPA thingie to generate a builder.

0 comments: