November 18, 2004

Casting null and failing fast

I never thought about it before, but it turns out you can cast null with no ill effects. Here's an example:

public class CastNull {
    public static void main( String[] args ) {
        Object someNull = null;
        String castedFromObject = (String)someNull;
        try {
            out( "Length: " + castedFromObject.length() );
        } catch ( NullPointerException e ) {
            out( "Caught NPE from castedFromObject" );
        }
        String castedFromNull = (String)null;
        try {
            out( "Length: " + castedFromNull.length() );
        } catch ( NullPointerException e ) {
            out( "Caught NPE from castedFromNull" );
        }
    }
    private static void out( String msg ) {
        System.out.println( msg );
    }
}

I had expected this to die at the two String casts. Nope. Each dies when you try to call a method on it -- this will print out both of the 'Caught NPE' lines from the catch blocks. If you think about null as an instance of Object (which happens to be null) then it makes sense, but doesn't the fail-fast principle tell us we should instead die at the cast?

Next: Benefits of writing software quickly
Previous: Join with the creationists!