Sunday, January 22, 2012

Writing good static argument validation methods

Before we get into the NullObjectProxy class there is one more prerequisite to get out of the way.
How many times did you have to write the following kind of code:
// Example (1)
if (parameter > limit)
    {
    throw new IllegalArgumentException (
            "'parameter' is too large: " + parameter + " > " + limit);
    }
I decided that I had enough of this and that I wanted to be able to write something like:
// Example (2)
validate (parameter > limit, "'parameter' is too large: " + parameter + ">" + limit);
However, a little thinking made me realize that this form is not really appropriate and would have annoying side effects. In this specific case a bunch of Strings would be allocated and concatenated each time the method is called and that is not good since it would make calling the method very different from the initial code. I did a little more thinking and I came up with:
// Example 3
validate (parameter > limit, "'parameter' is too large: &1 > &2", parameter, limit);
The implementation for this is shown below:
Here is the getFormattedMessage(..) method:
Now with this version what you have on each call is that a few arguments are pushed on the stack. You still have annoying side effects though. You still get an Object[] allocated and filled on each call. Also, if you have primitive arguments you get autoboxing of those into primitive wrapper classes (Integer, FLoat, ...). Of course you can further optimize this by having different versions of the method with different primitive arguments. Fortunately it is easy to define such methods for the most common cases. Here is an example with two int arguments:
public static final void validate (boolean condition, String formatString, 
              int firstValue, int secondValue)
Those methods are defined in a static utility class called Verification and this class contains one and two arguments versions for all primitive number types. Now, the validationFailure(String, Object ...) is called only if the condition fails and so objects are allocated only on failures. We at last have something close enough to the original construct that we can use on a routine basis.
I was so pleased with this that I added a validateNotNull(boolean, String, Object ...) method:
// Example (4a)
public static <T> T validateNotNull (T value, String formatString, Object ... arguments)
This is a generic method that will handle any type of reference and return the correct type (no cast needed). I also have a short form for this:
// Example (4b)
public static <T> T validateNotNull (T value, String parameterName)
This short form will print a predefined message:
parameterName should not be null
You can use those methods like this (short form):
// Example (5)
SomeType localVariable = validateNotNull (parameterOfSomeType, "parameterOfSomeType");
The verification class also contains a number of expect(boolean, String), expect(boolean, String, Object ...) and expectNotNull(Object, String) methods. Those are used to test other conditions that would normally throw IllegalStateExceptions.
Ok, now your thinking "that's a lot of trouble for an assert mechanism". The reason I don't use the Java assert mechanism for this is that:
1) I don't want it to be possible to disable those verifications and I want them enabled by default.
2) My Verification class methods have a very usefull trace mechanism build-in. When activated this trace will always get printed even if exceptions are thrown away or lost (handled improperly in thread, ...).
I really like those little methods and I use them a lot. They make it really easy to build meaningful error information reporting into the code.
Of course I will use them in my next blog about my new NullObjectProxy class.

Wednesday, December 28, 2011

When is it ok to use method overloading in Java ?

In his excellent book Efficient Java Programming, Joshua Bloch has an item titled:
Item 41: Use overloading judiciously
Because I'm going to use method overloading in my NullObjectProxy implementation I will give some additional information about when it is ok to use method overloading. I highly recommend that you read Item 41 but here is a little extra graphic help and also a relaxation of Joshua Bloch's criteria. To simplify the presentation I will assume that the return type of all methods here is void and I will not include the return type in the examples. For a method m(t1 x1, t2 x2, ..., tn xn) where t1 to tn are the n parameter types it is safe to create an overloaded version m(t'1 x1, t'2 x2, ..., t'n xn) if for each type ti (i=1 to n), t'i is not a subtype or supertype of t.
Lets look at a few examples. We will base those examples on the set of classes illustrated here
We will use a one parameter method as our existing method to overload: m(Class-X x1)
The following overloaded versions would be ok:
m(Class-Y x1)
m(Class-Z x1)
The following would not be ok:
m(Class-A x1)
m(Class-d x1)
Had the original method been m(Class-A x1) there would have been no safe way to overload using the types in the diagram.
Had the original method been m(Class-d x1) then the following overloaded versions would have been ok:
m(Class-Y x1)
m(Class-Z x1)
But m(Class-A x1) or m(Class-X x1) would not be safe.
You get the idea.

Saturday, December 24, 2011

Learning from experience

Since my last post I have had several occasions of using my NullObjectProxy class in practice. I learned a lot from that. The first thing I realized was that I needed to allow defining behavior for the Object class methods (hashCode, equals, toString). Used in the confined environment of unit tests this was not obvious but used in real code it really became evident that this was needed. In fact I decided that I needed to provide a default coherent behavior for those methods.
I also realized that I needed to provide a more sophisticated method of defining return value even for a Null object.
The result of all this was that I modified my initial code quite a bit. So in my next post I am going to start over on the NullObjectProxy and used the updated more sophisticated version of this class.

Monday, August 22, 2011

The Builder and Null Object pattern meet the Java Proxy class

I love the Null Object pattern. It is a simple and useful pattern in many situations. The archetypal example is in the context of JUnit tests (or whatever is your favourite testing framework). In unit tests, Mock objects are often little more than Null Objects. Obviously, there are very good libraries for mocking objects in unit tests and I guess I could use this for Null objects in regular code but that would bring a lot of dead code into my application since those libraries provide some pretty fancy features. I need something simpler.
I have used the Java dynamic java.lang.reflect.Proxy class for things like debugging proxy and other applications so I though using this class for Null Object would be great (if you need a refresher on Java Dynamic Proxy check Explore the Dynamic Proxy API). In fact since a Null object has only one immutable state you only have to worry about the return value of its method. I want to keep this simple so what I will do is I will use two Map(s) in my proxy handler: one with return types for keys (Class) and one with method names for keys (String). This will allow me to define return value for different return types and return values for different method names. This implementation does not support having different return value for methods with the same name and different parameters (overloaded methods). This should not be a big limitation since a Null object is likely to return the same value in this case. Here are the declarations for my Map(s):
The returnTypeLookup must include values for primitive types since methods that return those cannot default to null. As a bonus the Map includes a consistent set of values for primitive wrapper classes.
The code below shows how the Map(s) are used in the invoke method of my handler:
As you can see we first check if there is a custom return value for the invoked method name and then we check if there is a custom value for the return type. This makes it possible to handle most common cases where you want to override the default.
Now how can we customize our Proxy ? We could use different constructors for our invocation handler or some extra methods to override values. I have considered several options and finally I think I have found a very elegant solution. Here is what creating a Null object using my API looks like:

ISomeInterface r = 
	NullObjectProxy.newInstance (ISomeInterface.class)
		.whenReturnType (boolean.class, true)
		.whenMethodName ("someMethodName", new SomeUserDefinedType())
		.build ();
To achieve this I use a generic Factory method and a Builder class.In my next post I will show you how to define a class that can be used with such a flexible and programmer friendly syntax.


Wednesday, July 6, 2011

Microsoft and Oracle killing the cash cow

I don't know if Microsoft and Oracle realize that they have to be careful in their battle with Google and Android. Personally, I think this whole patent business could end up killing the cash cow or at least weakening it quite a bit. The Android technology has created a very dynamic ecosystem that has generated what I think is a non negligible amount of business activity. Both Microsoft and Oracle are probably already benefiting indirectly from this economic activity. I wonder how many developers are running Eclipse using Oracle JRE and using the Android SDK on Windows based PCs.
Instead of being always destructive maybe Oracle and Microsoft should start to think about how they could benefit from the Android platform (I know, that sounds weird). I'm sure they would find some positive ways to get money out of the platform.

Friday, December 25, 2009

My first JavaFX script

I just wrote my first JavaFX script. This script is actually a little benchmark I run when first looking at a new language. Is it rigorous and scientific ? Not at all. It is a very modest benchmark that gives me a feel for the language speed. It includes a bunch of operations typical of the kind of code that I write (string manipulations, collection manipulations, etc...). The code is not optimized to any degree and might actually run faster (or slower) if I was to use more idiomatic style. I also use a number of Java class. I think this is needed because this is also representative of what actual code will look like.
So what is the result ? Turns out that in this benchmark JavaFX is only 2 times slower than Java (511 milliseconds in one tests compared to 272 using Java). If you compare that to other JVM languages that is actually quite good. Groovy for example runs this particular benchmark in about 2600 millis (about 5 times slower than JavaFX). Of course JavaFX is a statically typed language so I was hoping I would get that kind of performance. I suspect that this will improve with subsequent versions. Scala for example runs the benchmark in about the same time as Java.
Of course speed is not the only criteria for language selection. Groovy for example being a dynamic language has a lot of characteristics that make it really appealing. However, in my case for the kind of applications I work on I cannot run 10 times slower than Java. If I can write only a small portion of an application using a language then this language becomes much less interesting. With the kind of speed that JavaFX is giving me I know I can write most of my code using it. That makes it really appealing. Now if JavaFX graphic rendering can get fast enough and with its already compeling UI capability it becomes a clear winner in my book.

Sunday, November 1, 2009

In a previous blog I mentioned using DbC as a technique on a project. I forgot to mention one important element that is very important in DbC and that's invariants. Since I did not use any fancy tools to work with DbC I had to find a way to define invariants. I choose to simply define a private method called invariants and added a call to this method in a conditional compile block at the beginning and end of every public methods. Like I said in my previous discussion this simple way of using DbC adds a bit of clutter to the code but this is a small cost to pay to get the benefit of DbC.
Invariants are assertions about a class that are always true. For a linked list for example:

first != null || size == 0

Combined with preconditions and postconditions the impact on code correctness is just amazing. Thinking about the assertions just get you there faster.
On my next project I just might use Microsoft's Contract tool. The only annoying thing is that I probably won't be able to use this with MONO.