← All blog posts

The Null Ambiguity

May 19, 2018 · Programming

Overloading constructors in Java (not only) is good for the overall design. When used effectively it can result with correct and efficient initialisation of a class and avoidance of many lines of boiler-plate code.

Yesterday, I stumbled on the following problem. I wrote a class like the following:

public class Foo {
public Foo(Integer i, Double d) { ... }

public Foo(Integer i, Float f) { ... }
}

which defines a class Foo with two constructors that accept Integer and Double, and Integer and Float.

For some reason (not important right now) I wanted to initialise the first (Integer,Double) with the second parameter set as null.

This resulted as a compiler error, because the compiler actually could not decide which of the two constructors I wanted to use. Whoops … what could I do?

I could introduce a third constructor, with only one parameter and call this. Try it, you will see, that you will end up using part of the initialisation of the two others, which may complicate things (at least it did in my case).

Fascinating, isn’t it? Maybe we need a Null<Double> or Null<Float> to avoid this mess? Maybe the null value should be a generic Null<T> and use it to ensure type safety and instruct the compiler to correctly solve this ambiguity?

I do not know. My real-world problem solved with a third constructor as a work-around and some duplication of code. C’est la vie.