Skip to main content

Commons-chain: a few tips.

Posted by dcengija on March 8, 2005 at 7:08 AM PST

ONJava.com published an article titled "A Look at Commons Chain: The New Java Framework" by Bill Siggelkow. Being a commons-chain user myself for some time now, I thought people might find useful a tip or two.

Return value

I find very confusing the return policy of the chained commands. If you want your chain to continue, then return false, if you want it to stop, then return true. Solution: create a CommandBase abstract class and make all of the commands extend it. Next to the common methods your command will probably need, put something like this:

    public static final boolean CHAIN_STOP = true;
    public static final boolean CHAIN_CONTINUE = false;

Now, instead of returning false or true in your execute methods, return CHAIN_CONTINUE or CHAIN_STOP. It makes your code much more readable, at least for me.

Spring configuration

If you don't use Spring, well, you should start using it :-) I'm very happy with it and somehow I thought Spring should be able to configure the chains as well. And of course, it is. This piece of Spring's context config file should help you get started:

        <bean name="myExecutionChain" class="org.apache.commons.chain.impl.ChainBase">
                <constructor-arg>
                        <list>
                                <ref bean="firstCmd"/>
                                <ref bean="secondCmd"/>
                        </list>
                </constructor-arg>
        </bean>

        <bean name="firstCmd" class="...SomeCommand">
                <property name="...">
                </property>
        </bean>
        <!-- and other commands -->

        <bean id="chainRunner" class="...ChainRunner">
                <property name="executionChain">
                        <ref bean="myExecutionChain"/>
                </property>
        </bean>
ChainRunner obviously has setExecutionChain method and triggers the chain's execute() method. I'm leaving this part to you as a homework :-)

And that's it for now. More tips will come as I progress in my usage of commons-chain.

Related Topics >>