This is completely reliant on the problem domain and how the interface is used. I have written interfaces both ways.
I have seen SOAP libraries not allow null values, making Integer
completely unnecessary.
On the flip side, I have used Integer
for cached data (you specifically mention "instance variables" in your question, not just the API):
public class Test implements Serializable { private transient Integer hash; public int hashCode() { if (hash == null) { hash = <time-consuming hash operation>; } return hash.intValue(); } }
In this case, the object is being used as a key in a HashMap
so it makes sense to cache a hash value rather than recompute it over and over. Using Integer
means I can say with 100% certainty that I have already computed the value or not (as opposed to String
's sentinel value which in theory can produce a hash collision).
If an API accepts Integer but assumes not null, that is a fail-fast scenario. It will throw a NullPointerException
and should do so quickly. Client code using your API should encounter this exception rather quickly, making it easy to find and fix the bad data when testing.
I recommend using Integer
(maybe with Optional to make it clear) for optional data, and int
when it is required.