Fun-Guice (Guice function extension)

26 views
Skip to first unread message

Brian Slesinsky

unread,
Nov 19, 2007, 4:27:40 AM11/19/07
to google...@googlegroups.com
I was thinking about scopes and the "robot legs" problem and came up
with another idea: function bindings with Guice. I implemented a
little demo that's hardly production-worthy, but I thought you folks
might find it interesting. Here's an example:

public void testRecursiveFunctionImplementedAsProvider() throws Exception {
FunInjector injector = FunGuice.createInjector(new FunModule() {
protected void configure() {
bindFunction(Integer.class, Integer.class)
.toProvider(FactorialProvider.class);
}
});

Function<Integer, Integer> factorial =
injector.getFunction(Integer.class, Integer.class);
assertEquals(1, (int) factorial.make(1));
assertEquals(2, (int) factorial.make(2));
assertEquals(6, (int) factorial.make(3));
assertEquals(24, (int) factorial.make(4));
}

private static class FactorialProvider implements Provider<Integer> {

@Inject
private int parameter;

@Inject
private Function<Integer,Integer> factorial;

public Integer get() {
if (parameter == 1) {
return 1;
} else if (parameter > 1) {
return factorial.make(parameter - 1) * parameter;
} else {
throw new RuntimeException("not implemented for " + parameter);
}
}
}

You can download the source here:

http://slesinsky.org/brian/downloads/fun-guice.zip

You might also find RequestScopeTest interesting; it shows various
ways to implement request scopes using functions.

- Brian

Reply all
Reply to author
Forward
0 new messages