Java Reference
In-Depth Information
Here's a JUnit 4 test (written in Java, so it's an example of Java/Groovy integration itself)
that takes advantage of that constructor:
public class ImmutablePointJUnitTest {
private ImmutablePoint p;
@Test
public void testImmutablePoint() {
p = new ImmutablePoint(3,4);
assertEquals (3.0, p.getX(), 0.0001);
assertEquals (4.0, p.getY(), 0.0001);
}
}
This, again, works just fine. At the moment, my IDE even understands that the two-argu-
ment constructor exists, which is pretty sweet. I'm using the three-argument version of the
Assert.assertEquals method, by the way, because I'm comparing doubles, and for
that you need to specify a precision.
There's also no need to try to check for immutability, because from the Java point of view
the class has no methods to invoke that might change x or y . Unlike the getX and getY
methods shown, there are no corresponding setters.
As I say, this all works, but if you're trying to use the generated constructor and your sys-
tem refuses to believe that one exists, there's a simple workaround. Simply add a factory
class in Groovy that can instantiate the points in the usual way:
class ImmutablePointFactory {
ImmutablePoint newImmutablePoint(xval,yval) {
return new ImmutablePoint(x:xval,y:yval)
}
}
Now the Java client can instantiate ImmutablePointFactory and then invoke the
newImmutablePoint factory method, supplying the desired x and y values.
Everything works, that is, until you succumb to the temptation to follow standard practices
in the Java API and make the factory class a singleton. That's the subject of the next sub-
section.
Search WWH ::




Custom Search