The power of XMLUnit with google Predicate

I have been interested in XMLUnit and google collections predicate system for awhile now and recently wrote the following as part of a test.  I have removed some of the test and left just the bits that illustrate this point.

The test needs to perform a check that the result of transforming some xml is correct.  A reference file is available so we can use XMLUnit to perform a difference.  In my file there is a seconds attribute and because seconds vary with each parse we choose to ignore the value.  There are other ways to achieve this, but its more complex and uses more XMLUnit code. Using a google predicate simplifies this check.

First produce your output file and load the sample and output into strings. Normally for a test I produce a smaller sample xml file. Then using XMLUnit difference engine get all differences.

    Diff d = new Diff(expectedAsString, outputAsString);
    DetailedDiff dd = new DetailedDiff(d);
    List listOfDifferences = dd.getAllDifferences();

Next call a function to check that the only differences found are within the seconds attribute. This uses a predicates from google to perform the matching.

    assertTrue(onlyDiffsMatchThisAttributeName("seconds",listOfDifferences));
    }

    private static boolean onlyDiffsMatchThisAttributeName(final String attrName, Iterable it) {

    Iterable filtered = Iterables.filter(it, new Predicate() {

        @Override
        public boolean apply(Difference input) {

                final NodeDetail testNodeDetail = input.getTestNodeDetail();
                if (nodeDetail == null) return false;

                final Node node = nodeDetail.getNode();
                if (node == null) return false;

                final String nodeName = node.getNodeName();
                if (nodeName == null) return false;

                return !nodeName.equals(attrName);
            }
        });
        return (newArrayList(filtered).isEmpty());
    }

Note that what is happening here is the predicate is filtering away all the seconds matches. If anything remains in the list false is returned. Neat huh! :-)

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)

Google Objects.equal, useful but be careful.

Google have a nice equals method to make boiler plate equals easier to read. Particularly good if you have many attributes in the method. http://publicobject.com/2007/09/coding-in-small-with-google-collections_8175.html

Be careful to check that your objects are consistent with equals though.  I have mentioned this before.
Continue reading

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)

Eclipse, Static imports quickly and GitHub gist.

Every one has a collection of favorite Eclipse templates.  I find the simple ones are often the most useful.  The examples below create you a static import and finish the method your typing.  They even put the cursor in the right place if you need arguments in the method.  I am going to collect more of them using the incredibly handy GitHub gist: My Static Import Templates For Eclipse.  GitHub gists are great for these kinds of programmer reminders.  In addition edits get version control.

Typical Eclipse template for Google Collections

${:importStatic(com.google.common.collect.Lists.newArrayList)}newArrayList();
${cursor}
${:importStatic(com.google.common.collect.Sets.newHashSet)}newHashSet();
${cursor}

To use them, just open Eclipse Preferences: Java Editor: Templates.  Add new templates, and give them a name similar to the method.  I.e newArrayList.  Then your code completion hot key will run the template completing the text your typing in.  i.e you type newArrayList [code complete key] and it adds the static, and the rest of the method, placing your cursor at the end of the line.  Neat!

Note: See the comment from Yuri below, the above templates are no longer required for static imports. Its possible to configure the Content Assist to bring in a whole type, or member using Prefs:Java:Editor:Content Assist:Favorites. This is better as it scans all possible available methods in the type.

The code you end up with is tidy too:

List myList = newArrayList();

There is another thing I can never remember the syntax for! :-)   The markup to add the syntax highlight for this blog. Available as a gist: http://gist.github.com/234709

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)

When you can’t avoid an out parameter

We all know its a good idea to avoid using out variables in Java. In almost every case the code can be split up to avoid the situation. Its bad semantics because when reading the code its not obvious which object passed, if any will get mutated.  So the reader is forced to open the method to find out what it does. In Robert C Martin’s Clean Code Book he calls this forcing a double take, and suggests some ways to avoid the problem.  Rarely you find a case where you can’t avoid it, or to be more accurate, avoiding it leads to worse problems.

Take a look at this interface.  If I find this populate method, I am likely to have to open implementations.  I don’t know if it populates one map from the other or both maps.

import java.util.Map;

public interface NastyPopulator {

void populate(Map<String, String> driver, Map<String, String> driverHolder);

}

The problem is the semantics of map are that you can read from maps or you can write to them.  I think this is a slightly better approach below.

I have used ImmutableMap.Builder.  The semantics of this are that it is used to build things.  I will call build() on the object later to get a map.  Next its an ImmutableMap.  So not only am I declaring that the two parameters are likely to be used to build something, that thing will ultimately be Immutable so in effect the signature declares that I am not expected to make modifications later.  Finally the method name is unambiguous buildMaps, which pretty much says what its going to do.

import com.google.common.collect.ImmutableMap;

public interface LessNastyPopulator {

void buildMaps(ImmutableMap.Builder<String, String>  driver, ImmutableMap.Builder<String, String> driverHolder);

}

Feels like a stronger declaration to me. If ImmutableMap is awkward you could define your own static builder and pass that in, at least your still declaring up front, that this method is builds the two maps. If the method is reading from one map and building others, how about passing an iterator and a builder?

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)