Careful with constructor or method overloading

Method overloading is a useful and powerful concept. It helps to keep code more easily readable and understandable by allowing the same method name to be used with different parameters and by allowing several constructors to be defined with different parameter sets.

Unfortunately, the results can sometimes be quite surprising.

Consider the following constructors.

public CustomException( int exceptionCode, Throwable cause, Object... parameters );
public CustomException( int exceptionCode, Object... parameters );

These are used to define an translatable exception. The actual message is obtained through a message bundle and some addition parameters can be passed which can be included in the message. To make it easier for the user, the parameters are of type “Object” instead of “String”. This avoids the need for explicit invocation of “toString()”.

Now consider a use of this exception

catch ( IOException ioe )
{
    throw new CustomException( ExceptionCode.WRAP_IO_EXCEPTION, ioe, filename );
}

I would expect that the most specific constructor would be called, the one where the cause throwable. Unfortunately that does not work. Some rewriting into

catch ( IOException ioe )
{
    throw new CustomException(ExceptionCode.WRAP_IO_EXCEPTION, ioe, new Object[]{ filename } );
}

Did not help. As the object array is also an object, the java compiler cannot make the distinction.

The only solution is to change the signatures into something like

public CustomException( Throwable cause, int exceptionCode, Object... parameters );
public CustomException( int exceptionCode, Object... parameters );

Leave a Reply

Your email address will not be published. Required fields are marked *

question razz sad evil exclaim smile redface biggrin surprised eek confused cool lol mad twisted rolleyes wink idea arrow neutral cry mrgreen

*