JewelCli accessor method names

JewelCli 0.8.2 and above supports query methods with or without the “get” prefix:

public interface MyExample
{
  @Option
  String getMyOption();
 
  @Option
  String myOtherOption();
}

The instance strategy now supports mutators with or without the “set” prefix:

public class MyExample
{
  @Option
  void setMyOption(String value) {}
 
  @Option
  void myOtherOption(String value) {}
}

JewelCli Constrained Multivalued Option

A new feature in JewelCli 0.8.1 is the ability to constrain the multiplicity of multivalued options. If the arguments given by the user do not match the constraints an appropriate ArgumentValidationException is thrown.

Minimum

public interface ListWithMinimumOfOne {
    @Option(minimum = 1) List<String> getMyOption();
}

Maximum

public interface ListWithMaximumOfFour {
    @Option(maximum = 4) List<String> getMyOption();
}

Exact Count

public interface ListWithExactlyThree {
    @Option(exactly = 3) List<String> getMyOption();
}

JewelCli Hidden Options

As of version 0.8.1 JewelCli supports hidden options. These are options that will not show up in your help message.

interface HiddenOptionNotIncludedInHelp
{
     @Option(hidden = true)
     boolean getDebug();
}

Will create an option called “–debug” which you can specify on the command line, but will not be advertised in any help messages.

EventCast Whiteboard Pattern (Listeners Considered Harmful)

The first time I encountered the whiteboard (or blackboard) pattern was when reading the pragmatic programmer. Since then I have seen it a few times. The major mainstream use of the whiteboard I have seen is in Dependency Injection frameworks like Google Guice and Spring.

In my opinion these DI frameworks might better be described as an implementation of the whiteboard pattern for service (dependency) location and contribution, which also do dependency injection. They can provide you objects from the whiteboard – one way they do that is by DI. But they also can do it in other ways, the Guice Injector can be used as a factory directly (using the getInstance method). Or by providing factory implementations (Providers or my favourite AssistedInject) that draw objects from the whiteboard.

In particular, this is very helpful when an application is structured for testability in a ports and adapters architecture. I am aware that Nat Pryce has an issue with DI frameworks not distinguishing between internals and peers, but I don’t think I have really run into that problem practically. I think probably he is also making the point that DI libraries can hide important information about how you objects are put together. I think both issues probably depend on how you use the DI library and which objects you choose to put into its whiteboard – in general avoid hiding the rules about relationships between your domain objects in your DI usage. BTW; I don’t think EventCast hides relationships in general (actually the opposite), but I can see how it could be used to do that.

So, onto the main point of this post.

The OSGi framework uses the whiteboard pattern to manage dependencies between bundles. In particular when one bundle is driven by events from another (supporting IoC). There is a provocatively named paper called Listeners Considered Harmful: The “Whiteboard” pattern on how they used the whiteboard pattern to replace the listener pattern.

I have recently been working on a library called EventCast based on my experiences using Guava EventBus. What it does is use Guice to implement the whiteboard pattern for OSGi style inter-object communication using interfaces to define the listeners (kind of a very light, stripped down, version of some of what you get with OSGi).

EventCast tries to be as unintrusive to the application code as it can. A single instance of the listener interface is injected into (hopefully the constructor(!) of) each object that wants to produce those events. Registering and unregistered of listeners (listener lifecycle), the threading model of the listeners and any listener error handling is managed separately from the producer. So your consumer just implements the interface it wants messages for, and your producer just calls methods on the injected instance of the listener interface. EventCast handles distributing the message to all of the currently registered listeners.

It is tightly integrated with Guice. It uses the Guice Whiteboard to store the EventCast listener implementation and make it available to the rest of the application. It detects additions of new listeners to the Guice Whiteboard and registers them for any produced events.

Guava EventBus Experiences

Edit 2012/12/13: I have created a library that corrects some of the issues I observed below in eventbus.

I have been using EventBus from the Google Guava library to create a customized installation system for bespoke software product consisting of a large number of components. Here are some of my experiences using the EventBus.

Using EventBus with Guice

I use Guice heavily in almost all of the new code I write. Guice is the new `new`. Using EventBus with Guava is straightforward. Just bind a type listener that will register every object with the EventBus.

final EventBus eventBus = new EventBus("my event bus");
bind(EventBus.class).toInstance(eventBus);
bindListener(Matchers.any(), new TypeListener() {
   @Override
   public <I> void hear(@SuppressWarnings("unused") final TypeLiteral<I> typeLiteral, final TypeEncounter<I> typeEncounter) {
       typeEncounter.register(new InjectionListener<I>() {
           @Override public void afterInjection(final I instance) {
               eventBus.register(instance);
           }
       });
   }
});

You get an instance of the event bus simply by using any of Guice’s normal dependency injection mechanisms:

class MyClass
{
   private final EventBus eventBus;
 
   @Inject
   public MyClass(final EventBus eventBus)
   {
      this.eventBus = eventBus;
   }
[...]

Listening for Events

To listen for an event, simply add the `@Subscribe` annotation to you class, and get an instance of that class from Guice.

@Subscribe
public void myEventHappened(final MyEvent event)
{
   // do work
}

Easy to miss off annotations in Guava EventBus

public void myEventHappened(final MyEvent event)
{
   // do work
}

If I miss an annotation off a subscriber method then nothing tells me something has gone wrong. The compiler won’t tell me, Guice won’t tell me, EventBus will happily register an object that has no subscribe methods at all. I have to write module level tests that check that all of my subscriber methods actually get called by the EventBus. This is fine, and I probably do that any way. But its easy to make a mistake, and I’d like either something more robust or “Guice-style” failfast.

Loose coupling between sender and listener

EventBus creates very loose coupling between the Event sending class and the Event listening class. The only thing that is shared between the two classes is knowledge of the Type of the Event that is being communicated. EventBus isolates the sending class from failures in the listening class. EventBus can also isolate the sending class from the performance of the listening class by using an AsyncEventBus.

Eventbus doesn’t work well with my normal IDE code navigation tools

Because of the very loose coupling between Sender and Listener, it can be hard to find all the methods that are listening for a given event (say) E.class. You have to do do a search like “find all occurrences of the class E” and then sort out which ones are your Subscribe methods. The same is true for finding all the senders of a particular event – you need to say “find all the calls to `post` that are given an argument with the runtime type E”. Both of these navigations are hard to do in an IDE I believe.

Inversion of Control

EventBus allows the wiring of the Sender->Listener relationship to come up to the top level of the application. Although this isn’t inherent in EventBus, the way it integrates with Guice provides a natural decoupled way to wire up your application. Exactly which EventBus instance each of your instance objects gets registered with and sends too can be configured using all the normal Guice features.

Eventbus gets coupled into your codebase

If a class needs to send a message it has to be injected with an instance of the Eventbus. If a class needs to subscribe to a message it has to have some of its methods annotated with the Subscribe annotation. I can wrap up the EventBus in my own custom wrapper, but that doesn’t fix the Subscribe annotation issue. I’d like something that has less coupling throughout my code.

Eventbus is hard to mock

I tend do use a lot of London-School (JMock) style unit tests. Eventbus is a little hard to use in this style. Two issues in particular are awkward: 1) Eventbus is a class with no interface, so mocking it requires a certain amount of technology and is generally not as clean as I would like. 2) The post method requires a single event object. I end up having to write custom matchers for each part of my event object I might be interested in, or implementing `equals`, `hashCode` and `toString` for all of my Event classes. With a normal method call, I can choose to be only interested that a particular named method gets called, or interrogate each of the arguments using any of the collection of Matchers that I have built up.

Eventbus causes the definition of lots of `event` classes

EventBus has the effect of forcing the developer to define all the events used by their application as Classes in the system (you can send any object as a message). This can be helpful in that it forces a clear definition of the message for each event. But it feels a little un-java-like in the sense that a message in Java is usually thought of as a combination of the method name and the method parameters. In EventBus the method name in the listener is irrelevant to the meaning of the message, and only one parameter is allowed in the `Subscribe` methods which is the Event instance. This overloads the parameter to contain both the data required by the `Subscribe` method and also to contain the meaning of the message. It also produces packing and unpacking boilerplate code, each send has to package the message up into the Event object and each `Subscribe` method has to unpackage the Event object.

Dynamic dispatch

EventBus events are delivered according to the runtime type of the event (similar to the way exceptions are caught). This allows `Subscribe` methods to be very specific about only responding to the exact even they are interested in, but it can make it a little difficult to reason about whether a particular call to post will cause a particular `Subscribe` method to be invoked.

Contest – concurrent testing using junit

Inspired by imunit I have put up a very early version of a concurrent testing library for junit which allows you to test your thread-safe objects with multiple execution schedules.

You can specify constraints on each schedule which contest will enforce – if the test progresses the execution schedule will meet the constraint (at the moment contest doesn’t detect impossible schedules or runtime deadlocks).

Tests look like this:

@Test @Schedules({
        @Schedule(
                when = AddAddRemove.class,
                then = SizeIsOne.class),
        @Schedule(
                when = AddRemoveAdd.class,
                then = SizeIsOne.class),
        @Schedule(
                when = RemoveAddAdd.class,
                then = SizeIsTwo.class)
}) public void twoAddsOneRemove()
{
    context.checking(new TestRun() {
        {
            inThread(Producer).action(FirstAdd).is(multiset).add(42);
            inThread(Producer).action(SecondAdd).is(multiset).add(42);
            inThread(Consumer).action(Remove).is(multiset).remove(42);
        }
    });
}

The following is a schedule constraint read as “Action FirstAdd happens before action Remove, and action SecondAdd also happens before action Remove“.

class AddAddRemove extends BaseSchedule
{
    {
        action(FirstAdd).isBefore(Remove);
        action(SecondAdd).isBefore(Remove);
    }
}

Theories are defined like this (using hamcrest matchers):

class SizeIsOne extends BaseTheory
{
     {
         asserting(that(multiset).size(), equalTo(1));
     }
}

Get it from maven central:

<groupId>com.lexicalscope.contest</groupId>
<artifactId>contest</artifactId>
<version>0.0.1</version>

Alpha: Lightweight Dynamic Proxy API

I have added an alpha version of a dynamic proxy API to fluent reflection.

It allows you to define Java dynamic proxies using a light-weight fluent syntax. It uses the same reusable hamcrest matchers that are used throughout the rest of the fluent reflection API.

Overview

For example, to proxy a simple interface like this

interface TwoQueryMethod {
   int methodA();
 
   int methodB();
}

You define a new class which extends com.lexicalscope.fluentreflection.dynamicproxy.Implementing. You can define as many methods as you like inside this class. Each method should start by asserting what it is proxying by declaring a hamcrest matcher to match against the method currently being proxied. The first matching method found will be executed.

In this simple example each method is matched by exact name, but the matchers can be as complex as you need them to be:

final TwoQueryMethod dynamicProxy = dynamicProxy(new Implementing<TwoQueryMethod>() {
   public void bodyA() {
      whenProxying(callableHasName("methodA"));
      returnValue(42);
   }
 
   public void bodyB() {
      whenProxying(callableHasName("methodB"));
      returnValue(24);
   }
});

Method Arguments

The arguments of the original method are available from the context provided by the Implementing base class

interface MethodWithArgument {
   int method(int argument);
   String method(String argument);
}
 
final MethodWithArgument dynamicProxy = dynamicProxy(new Implementing<MethodWithArgument>() {
   public void body() {
      returnValue(args()[0]);
   }
});

An alternative approach can be used if you know in advance what the arguments of the method will be. In this example a matcher which matches against the arguments of each body is implied. The body will only be called if the proxied method call has arguments that can be used to satisfy the requirements of the body:

final MethodWithArgument dynamicProxy = dynamicProxy(new Implementing<MethodWithArgument>() {
   public int body(final int agument)
   {
      return 42;
   }
 
   public String body(final String agument)
   {
      return "42";
   }
});

Introducing Fluent Reflection

I am in the processes of releasing the first alpha build of fluent-reflection, you can get the snapshot version from the fluent-reflection snapshot repository.

Motivation

Reflection code is difficult to write in Java, and even harder to read once it has been written. Although the Java Reflection API allows complete access to the Java runtime type system, the complexity of using the Java Reflection API reduces its usefulness. I don’t want to have to write any more code like this:

final List<Method> getMethods = new ArrayList<Method>();
 
Class<? super Bean> klass = Bean.class;
while (klass != null) {
   final Method[] declaredMethods = klass.getDeclaredMethods();
   for (final Method method : declaredMethods) {
      if (method.getName().startsWith("get") && 
          method.getParameterTypes().length == 0 && 
          !method.getReturnType().equals(void.class)) {
         getMethods.add(method);
      }
   }
   klass = klass.getSuperclass();
   [...]
}

Solution

There are three APIs which have heavily influenced the design of the fluent-reflection API.

  1. LambdaJ
  2. Hamcrest
  3. Jmock 2

All of them are examples of a style of API design known as fluent interfaces. They use a combination of static methods, method chaining, generic methods, static factory methods and object scoping to produce a type safe and readable programming style.

In particular, the combination of method chaining and generic methods can help the user discover the usage of each part of the API and also takes advantage of Java’s static type system to prevent programming errors.

Using fluent-reflection the above code can be re-written in declarative style:

final List<ReflectedMethod> getMethods = 
   object(new Bean()).methods(
      callableHasNameStartingWith("get").
      and(callableHasNoArguments()).
      and(not(callableHasVoidReturn())));

Extensibility

The query methods in the API are given queries described by Hamcrest Matchers. So users can easily construct custom and reusable queries.

For example, this Matcher can select methods with a particular annotation:

class MatcherAnnotatedWith extends ReflectionMatcher<ReflectedAnnotated> {
    private final Class<? extends Annotation> annotation;
 
    public MatcherCallableAnnotatedWith(final Class<? extends Annotation> annotation) {
        this.annotation = annotation;
    }
 
    @Override protected boolean matchesSafely(final ReflectedAnnotated item) {
        return item.annotation(reflectedTypeReflectingOn(annotation)) != null;
    }
 
    @Override public void describeTo(final Description description) {
        description.appendText("callable annotated with ").appendValue(annotation);
    }
}

Mashability

Because the API uses the de facto standard Hamcrest matchers, and the Java collections framework it can be combined with other libraries in powerful ways.

For example, calling all of the @PostConstruct methods on an Object using LambdaJ and fluent-reflection:

forEach(
   object(subject).methods(annotatedWith(PostConstruct.class)),
   ReflectedMethod.class).call();