More on Enums

Something that bothers me about Java Enums, is that they don’t represent ints out of the box.  Like no easy way to use them to represent particular indexes in an array, with the auto-incrementing thing happening, as per C/C++.

If you look a little deeper, there is the YOUR_ENUM.ordinal() method which will give you an int based on the position in your code that the ENUM_USED appears in the enum class, but the javadoc for ordinal makes you wary about using it

Returns the ordinal of this enumeration constant (its position in its enum declaration, where the initial constant is assigned an ordinal of zero). Most programmers will have no use for this method. It is designed for use by sophisticated enum-based data structures, such as java.util.EnumSet and java.util.EnumMap.

Returns:
the ordinal of this enumeration constant

"Most programmers have no use for this method"…. This method emulates the old C way of doing enums and not specifying a default.  Surely many programmers would be at home with such a thing?

…. is there a better way to represent static constants of indexes that don’t use an enum?

Well, there are some articles on this question, and what exactly the java enum implementation can and can’t do.

Making the Most of Java 5.0: Enum Tricks

This article contains some really clever things you can do with Java enums, like having a static block in the enum to initialise a static Map or even cooler, using Enums to implement Template methods.

AssumeThat(flexibleJunitTesting.withMatchers(), isGreat());

I’ve seen Matchers used in EasyMock but I kinda stumbled across the assertThat method in JUnit today and realised how powerful this stuff can be.

Usage:
assertThat(“You Failed”, testValue, allOff(greaterThan(3), lessThan(6))

They seem a lot simpler in this context even though they are the same thing.

The Matchers are taken from a project called Hamcrest which both JUnit, various xMock and other testing frameworks have all jumped on board to.

Hamcrest comes with a library of useful matchers. Here are some of the most important ones.

  • Core
    • anything – always matches, useful if you don’t care what the object under test is
    • describedAs – decorator to adding custom failure description
    • is – decorator to improve readability – see “Sugar”, below
  • Logical
    • allOf – matches if all matchers match, short circuits (like Java &&)
    • anyOf – matches if any matchers match, short circuits (like Java ||)
    • not – matches if the wrapped matcher doesn’t match and vice versa
  • Object
    • equalTo – test object equality using Object.equals
    • hasToString – test Object.toString
    • instanceOf, isCompatibleType – test type
    • notNullValue, nullValue – test for null
    • sameInstance – test object identity
  • Beans
    • hasProperty – test JavaBeans properties
  • Collections
    • array – test an array’s elements against an array of matchers
    • hasEntry, hasKey, hasValue – test a map contains an entry, key or value
    • hasItem, hasItems – test a collection contains elements
    • hasItemInArray – test an array contains an element
  • Number
    • closeTo – test floating point values are close to a given value
    • greaterThan, greaterThanOrEqualTo, lessThan, lessThanOrEqualTo – test ordering
  • Text
    • equalToIgnoringCase – test string equality ignoring case
    • equalToIgnoringWhiteSpace – test string equality ignoring differences in runs of whitespace
    • containsString, endsWith, startsWith – test string matching

Here is a summary of Matchers from the Hamcrest tutorial page.  They may not all be in JUnit.  JUnit ships with org.hamcrest.CoreMatchers and org.junit.matchers.JUnitMatchers.

Assumptions

Assumptions are like @Ignore-ing tests programmatically.  They are a test, intended to determine that the environment a test is running in, will successfully run the test.  The example from the JUnit 4.4 release notes best illustrates this:

import static org.junit.Assume.*  
@Test public void filenameIncludesUsername() {
assumeThat(File.separatorChar, is('/'));
assertThat(new User("optimus").configFileName(),
is("configfiles/optimus.cfg"));
}

If the expression in the assume statement fails, then the test will be marked as passed.  Apparently in future, the failed assumption may lead to the test being marked as ignored which would be excellent.

Edit: Another useful resource is the Junit API on Matchers

So you want to be a ClassLoader champion?

It wasn’t until earlier this year when I started learning Scala that I had to venture into how a class was loaded in Java.  It wasn’t that Scala required you to know it, it was simply that they made reference to the Java class path loading basics. I think it was to demonstrate that if you wanted to use Java class, where it would be pulled from and when.

 Previously, at best the only thing I’d had to worry about the order that classes were instantiated and by whom, mainly when sorting out issues of Hibernate either having Lazy cglib instantiations when they were meant to be real classes and vice versa.  A completely different problem but the only time I’ve had to worry about the way objects and classes come to being.

Yesterday while flipping through Head First Design Patterns, I also came across the discussion about Class Loaders when talking about Singletons and having two threads instantiate a Singleton class each and how to avert the problem.

 Today, one of the senior developers was summarising an issue we had at work and mentioned that our custom ClassLoaders used by our webstartable app may have been the cause of the problem.

The universe is asking me to learn about classloaders, hehe….

 So, in short, there are three class loaders in the JVM.

  1. Bootstrap class loader – loads all the classes/jars in the JAVA_HOME/lib directory
  2. Extensions class loader – loads classes/jars in the JAVA_HOME/lib/ext/   (Something reminds me here of the libraries Quicktime would install, and if not, those hooks that Mercury Quicktest Pro would use to get into your java app to automate it)
  3. System class loader – looks at your CLASSPATH variable

So you can make your own classloaders in addition to these.  Wikipedia’s article sights reasons of encryption, rmi, basically any time you need some dynamic class loading :).

 A google search was rich with resources:

JBoss wiki contains a tutorial on ClassLoading

The basics of Java class loaders

OnJava’s article: Internals of Class Loading

Get Fit

Fit is a framework that helps the business get involved in specifying the requirements that end up being the testing.  When the business can use Word and Excel to generate their own test cases, connected to a simple fixture and can be run by developers, customers and managers on demand, the potential for something great arises.

Encouraging the business to get involved at an early stage means that the business refine their requirements further.

Fit Tests can tell us useful things.  Where a FIT test fails, its an indicator that we need more code to cover business requirements.

Fit complements xUnit, the fixtures are similar but the test data, state and structure is all defined in the business supplied doco’s.  The fixtures are simply glue from these documents to the tests.

Automating Business Value with FIT and Fitnesse from InfoQ

Fit: Framework for Integrated Test

And when regular XP wont do, get Industrial XPNothing to do with FIT, just a site mentioned in the first link.

Now for something Obvious

In this presentation about FIT, the presenter, David, takes a look at the meaning of the term ‘the build is broken’.  What it is now compared to 10 years ago.  He states that as technologists we should be proud that we’ve evolved the meaning from the literal code broke, won’t compile, to now a meaning saying that the tests are broken. 

Given that in Eclipse, I’m told in almost realtime where compilation errors occur as I write them, and how this acheives high build success rate, I wonder if Eclipse can precompile and debug JUnit tests so that as we are changing code that is used in a test class, the test runs and the results are fed back in almost realtime, allowing us to pickup on even more potential hazards.

Lots of pitfalls for the cynical but its so crazy it just may work.

Hibernate Synchroniser

This article on OnJava.com demonstrates the use of the HibernateSynchroniser plugin for Eclipse that apparently keeps hbm mappings in line with Java code. 

 The page is a bit old but references Eclipse 3.2, so hopefully the plugin is still useful.

 I’ve been using the JBoss Hibernate Tools which just entered 3.2 GA and it seems to be making leaps and bounds.  The only crux is that you need to do a lot of preconfig work, it may be harder to introduce into an already established project that does its hibernate config programmatically.