according to Twitter subscribe to my twitter feed

    New year's resolution - be concise, but not terse

    I've just finished Strunk and White's classic The Elements of Style which I strongly recommend. It teaches you to review your writing before inflicting it on its readers. The book is under 100 pages which proves the authors understand concise use of the language. On top of that, it is an enjoyable little book to read. In the same way, the brevity of your coded language is important. Here's a great example from the Java api:

    Set<Colour> primaries = EnumSet.of(RED, BLUE, YELLOW);

    There is something beautiful about the perfectly-named method "of". Since Effective Java we all know to favour static factory methods over constructors. When dealing with generics it is even more important. Until constructor type inference arrives in Java, the constructor version would be comparatively cumbersome

    Set<Colour> primaries = new EnumSet<Colour>(RED, BLUE, YELLOW);

    In some future generation of the language, an operator overloading could provide more terse code. Maybe something like:

    EnumSet<Colour> primaries += {RED, BLUE, YELLOW};

    I'd argue that the of method is aesthetically more pleasing than the overloading. That's the difference between being concise and terse. Brief, clear and accurate, but not to the point of alienating those that have to read it.

    Labels: ,

    Java application config choices

    I took some good-natured jibing on my last project about the level to which I wanted to make the application configurable. My innate pedantry meant that I was driven to throw as much of the configuration and even logic into external files. Frameworks like Spring positively encourage this - why would you ever have a hard-coded static constant, when you can inject a value from xml? And why stop there - why not config your Spring config files with a PropertyPlaceholderConfigurer... Well, my colleagues have made me think a bit more about this approach. Clearly, there is some config data that no-one is quibbling about - database credentials for exmple, simply do not live hard coded into the application. But what about other meta data? Like say a number format pattern? Or an SQL string?

    There are lots of choices for where metadata can reside, and picking the appropriate one is key. Databases and properties files are great for config that often needs changing on the fly. For example, the number format for a column in an online report. However, they add a level of indirection during development which is anooying as the data is physically separated from the source. They are also not well suited to refactoring, although IDEs ease some of the pain these days.

    Annotations are at the other extreme as they are bound to the source. They're appropriate for a different category of metadata - when your config drives the code's core functionality. The classic example is a SQL (or an object query language) string which is well suited to living in annotated methods in DAOs. There is no point having it in an easliy-changed properties file because when you change your SQL you are fundamentally impacting the behaviour. That is not a runtime activity. However, annotations are more verbose to create. Moreover they are easily abused and overused resulting in bloated, messy code.

    As an aside, and a great example of annotation abuse, I really don't like JUnit 4's @Ignore - if the test is broken then fix the damn thing! That is just encouraging sloppiness. It is even worse than commenting out a broken test as it kind of looks official - like you somehow meant to do it. As much as I hate to admit it, at least a chunk of commented out test code is a big red flag that shouts at you to go back and get the thing to pass.

    So to sum up, the choices available in Java are increasing all the time. Spring for example ships with more and more annotations. In addition support is there for bean wiring by xml, properties files and programatically through the api. In a slightly obtuse way, their new dynamic language support can be thought of as config - you can certainly use it to inject new bahaviour at runtime. The choice can only be a good thing (I don't want to be forced to use EJB 2 deployment descriptors ever again). It just means I've got to think more carefully about where application metadata should live and not just dump anything that looks like config into properties files.

    Labels: , ,

    Easy transactional DAO JUnit tests using Spring

    This is nice quick win from the wizards at Spring. It is all in the doco, but I thought it was worthy of a post as it is very elegant. Unit testing a traditional DAO always gives the problem of what to do with test data that gets left in the database. Even if individual developers have their own database schema that gets cleared down and set up each time your test suite runs, you can get problems with data from one test polluting the next. In the worst case, your test cases start to depend on the order in which they're run.

    Spring provides an absurdly long named, but very handy superclass for your JUnit test cases: AbstractTransactionalDataSourceSpringContextTests

    Writing your test cases in a subclass of this will mean that each case seamlessly runs in its own transaction. Spring starts a transaction before the test case method is invoked, then rolls it back on completion (pass or fail).

    Here's an example:

    package io.serg.dao;

    import java.util.Collection;
    import org.junit.Test;
    import org.springframework.test.
    import io.serg.Customer;

    public class CustomerDaoTest extends
    AbstractTransactionalDataSourceSpringContextTests {

    private ICustomerDao customerDao;

    public void setCustomerDao(ICustomerDao customerDao) {
    this.customerDao = customerDao;

    public void testGetAllCustomers() {

    Collection customers = this.customerDao.getAllCustomers();

    The bean config to get this to work is very simple:

    <bean id="customerDao"

    <property name="dataSource" ref="dataSource"/>

    <bean id="dataSource"

    <property name="driverClassName" value="${jdbc.driverClass}"/>
    <property name="url" value="${jdbc.url}"/>
    <property name="username" value="${jdbc.username}"/>
    <property name="password" value="${jdbc.password}"/>

    <bean id="transactionManager"

    <property name="dataSource" ref="dataSource"/>

    Note that we're using Spring's autowire by type to inject the transaction manager into our unit test superclass. Still don't know what my feelings are about autowiring - my inate fear of all things magical means I'm trying to resist, but it does seem very neat in small examples like this.

    Clearly this is a very simple example, but more complex interactions with the database can be tested in this way, including the case where you do actually want to commit a transaction part way through a unit test (see the javadocs for org.springframework.test.AbstractTransactionalSpringContextTests, specifically the setComplete() method and defaultRollback property).

    This is a particularly sweet solution for the problem of unit testing your DAOs. You don’t need a separate test database per developer and you can run these concurrently and let the RDBMS handle the traffic.

    The principle argument against this technique is that you are still physically hitting the database so you are not just unit testing the DAO code. But in all honesty, unless you are going to mock up your datasource and jdbc connection (very painful) there is little alternative. In the real world, unless you go down the OR mapping route, your DAO and database are irrevicably linked. Furthermore, Spring allows you to write very clean DAOs which do almost nothing beyond handle the interaction with a relational database, so what else is there to test anyway?

    Labels: , ,